how to create table with 2 primary key fields hibernate - java

i'm trying to create tabel entity with composite primary key.
so i tried to create #Embeddable class with all the primary keys and use #EmbeddedId on the field that represents the primary keys. but i get this error:
Caused by: org.glassfish.jersey.server.model.ModelValidationException: Validation of the application resource model has failed during application initialization.
i wos tried to follow this link bat noting work
what i'm doing wrong?
here is my code
DocEntity
#Entity(name = "doc")
#Table(name = "doc")
public class DocEntity extends baseDataBase implements Serializable
{
private static final long serialVersionUID = 1L;
#EmbeddedId
private DocID docID;
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "DocID")
#JsonProperty
#NotEmpty
private short id;
#Column(name = "DocDescription")
#JsonProperty
#NotEmpty
private String docDescription;
#Column(name = "DocPath")
#JsonProperty
#NotEmpty
private String docPath;
// getters, setters ,equals, hashCode
}
DocID
#Embeddable
public class DocID implements Serializable
{
private static final long serialVersionUID = 1L;
#Column(name = "DocName")
#JsonProperty
#NotEmpty
protected String docName;
#Column(name = "DocVersion")
#JsonProperty
#NotEmpty
protected String docVersion;
// getters, setters ,equals, hashCode
}
what i'm doing wrong?

Related

How to update a record with a constraint and JPA?

I'm using JPA and I would like to update a record. I know that the save() method can update a record, but I have a constraint in my database and when I try to update the information I get the following error:
ERROR: duplicate key value violates unique constraint "register_code_package_unique_key"
Detail: Key (register_code, package)=(135, AL1689) already exists.
In my entity class those fields are this way:
#Entity
#Table(name = "packages", schema = "main", uniqueConstraints = {
#UniqueConstraint(columnNames = {"registerCode", "package"})
})
#Getter
#Setter
public class PackageEntity implements Serializable {
private static final long serialVersionUID = 1L;
#Id #GeneratedValue(strategy=GenerationType.AUTO)
#Column(name = "packageId")
private Integer packageId;
#Column(name = "registerCode")
private Integer registerCode;
#Column(name = "package")
private String package;
#Column(name = "registerDate")
private LocalDateTime registerDate;
#Column(name = "lastRegisterDate")
private LocalDateTime lastRegisterDate;
#Column(name = "employee")
private Integer employee;
#Column(name = "weight")
private Float weight;
}
How can I fix this error?

Why i get must use a #JoinColumn instead of #Column

i am tryning to join two entities where typDossAmo can have a list of DossMedic
but i get the following error:
Entity class [class ma.cnss.wstest.TypDossAmo] must use a #JoinColumn instead of #Column to map its relationship attribute [drugs].
public class TypDossAmo implements Serializable {
private static final long serialVersionUID = 1L;
#Column(name = "ID")
private BigInteger id;
#Id
#Basic(optional = false)
#NotNull
#Size(min = 1, max = 9)
#Column(name = "NUM_DOSS")
private String numDoss;
#Column(name = "p_tab_medic")
#OneToMany(mappedBy="doss")
private List<DossMedic> drugs;........
public class DossMedic implements Serializable {
private static final long serialVersionUID = 1L;
#EmbeddedId
protected DossMedicPK dossMedicPK;
#Column(name = "ID")
private BigInteger id;
#Column(name = "NOMBRE")
private BigInteger nombre;
#ManyToOne(fetch=FetchType.LAZY)
#JoinColumn(name="NUM_DOSS")
private TypDossAmo doss;
The idea of the annotation #Column is for common columns without any relationship with other tables, when you use #JoinColumn is to say to the ORM that two tables have a relationship and the way to join them is with this column.
In this case the solution is change the annotation #Column by #JoinColumn in TypDossAmo
public class TypDossAmo {
#JoinColumn(name = "p_tab_medic")
#OneToMany(mappedBy="doss")
private List<DossMedic> drugs;
}

Entity without Primary Key ID

Hi I want to create an Entity which doesn't have an ID.
#Entity
#Table(name="USER_PROD_LIC_TYPE_ALL")
public class UserProdLicTypeAll {
#EmbeddedId
private UserProdLicTypeAllPK id;
#ManyToOne(fetch=FetchType.LAZY)
#JoinColumn(name="USER_ID")
private User user;
#ManyToOne(fetch=FetchType.LAZY)
#JoinColumn(name="LICENSE_TYPE_ID")
private LicenseType licType;
....
}
since it doesn't have primary key i created Embeddable class as below:
#Embeddable
public class UserProdLicTypeAllPK {
#ManyToOne(fetch=FetchType.LAZY)
#JoinColumn(name="USER_ID")
private User user;
#ManyToOne(fetch=FetchType.LAZY)
#JoinColumn(name="LICENSE_TYPE_ID")
private LicenseType licType;
...
}
The combination of these two fields returns a unique value.
But it doesn't work. I get
org.springframework.beans.factory.UnsatisfiedDependencyException: exception.
Do i need to have references in User and LicenseType entities for both UserProdLicTypeAll and UserProdLicTypeAllPK? I have tried that also but still it doesn't work.
This is my private hell. I'm not sure what the best way to solve it properly.
My best solution is:
#Entity
#Table(name = TableName.AREA_USER)
#IdClass(UserAreaPK.class)
public class UserArea implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#Column(name = UserAreaPK.C_AREA_ID)
private Long areaId;
#Id
#Column(name = UserAreaPK.C_USER_ID)
private String userId;
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name = UserAreaPK.C_AREA_ID, insertable = false, updatable = false)
private Area area;
And
/**
* Primary key for the relationship User-Area
*/
public class UserAreaPK implements Serializable {
protected static final String C_AREA_ID = "area_id";
protected static final String C_USER_ID = "user_id";
private static final long serialVersionUID = 1L;
#Id
#Column(name = C_AREA_ID)
private Long areaId;
#Id
#Column(name = C_USER_ID)
private String userId;

Hibernating - Generating part of a composite key

I have the following class:
#Entity
public class User {
#Embeddable
public static class Key implements Serializable {
private static final long serialVersionUID = 1L;
private int id;
#Temporal(TemporalType.TIMESTAMP)
private Date effectiveDate;
#Column(unique = true)
private String name;
// Getters, Setters
}
#EmbeddedId
private Key key;
#Column(nullable = false)
private String password;
// Getters, Setters ...
}
I want the id field within key to be generated, unfortunately I can't find a way to do so. I've looked at similar questions here but I can't find the answer (all the solution proposed did not work in this case).

JPA - manytoone cascading

I've got two entities
ServiceDownload.java
#Entity
public class ServiceDownload implements Serializable {
private static final long serialVersionUID = -5336424090042137820L;
#Id
#GeneratedValue
private Long id;
#Length(max = 255)
private String description;
private byte[] download;
private String fileName;
#ManyToOne
private Service service;
Service.java
#Entity
public class Service implements Serializable {
private static final long serialVersionUID = 4520872456865907866L;
#EmbeddedId
private ServiceId id;
#Length(max = 255)
private String servicename;
#Column(columnDefinition = "text")
private String highlightsText;
#Column(columnDefinition = "text")
private String detailsText;
#Column(columnDefinition = "text")
private String productText;
#Column(columnDefinition = "text")
private String dataText;
#ManyToMany(mappedBy = "services")
private Set<Machine> machines;
#OneToMany(targetEntity = ServiceDownload.class)
private List<ServiceDownload> serviceDownloads;
#OneToOne
private ServicePicture servicePicture;
When I create a new ServiceDownload Object and try to persists this I recieve a duplicate key exception. It seems that jpa tries to insert a new service object into the service table. How can I disable this behaviour?
You are using #GeneratedValue annotation for your #Id. According to JPA documentation, you should supply unique identifiers
By default, the application is responsible for supplying and setting entity identifiers (see #Id)
Try using a #SequenceGenerator and a sequence in your database to generate unique identifiers

Categories