Sql Jpa - Multiple Columns As Primary Key
Solution 1:
You need to have a class for your composite key:
publicclassCompositeKeyimplementsSerializable {
privateint column1;
privateint column2;
privateint column3;
}
and then in your entity class use the @IdClass annotation:
@Entity@IdClass(CompositeKey.class)
public class EntityExample {
@Id
private int column1;
@Id
private int column2;
@Id
private int column3;
...
...
}
I think this should work. Hope it helps, cheers!
Yea and there is the other solution, the one that @jklee mentioned, both work, it's a matter of preference.
Solution 2:
Use @Embeddable and @EmbeddedId.
Example:
@Entity
public class Project extends Serializable {
@EmbeddedId ProjectId id;
}
@Embeddable
class ProjectId extends Serializable {
intdepartmentId;
longprojectId;
}
More information here http://www.objectdb.com/java/jpa/entity/id#Embedded_Primary_Key_
Solution 3:
If all fields in the class are part of primary key, then solution would be pretty simple (extending solution provided by @raul-cuth):
@Entity@IdClass(EntityExample.class)
public class EntityExample implements Serializable {
@Id
private int column1;
@Id
private int column2;
@Id
private int column3;
}
Solution 4:
- Using
@IdClassannotation on the@Entityclass followed by@Idannotation on individual fields that are part of composite primary key. - Alternatively can make use of
@Embeddableclass which can consist of individual fields of the composite primary key and then a reference of this class can be used as an attribute with@Embeddedannotation in@Entityclass. Hope this helps.
Solution 5:
Be aware that the hibernate Entity-Class-to-SQL-DDL-Script generator will sort all the fields, and irrespective of the order in which it appears in the definitions, will create the table definition and the index / constraint definitions in this sorted order of the fields.
While the order of appearance of the fields in the table definition may not matter much, the order of fields in a composite index definitely do. So your key-fields must be named so that when sorted by their names they are in the order you desire for the index).
Post a Comment for "Sql Jpa - Multiple Columns As Primary Key"