SQL JPA - Multiple columns as primary key

前端 未结 5 1377
猫巷女王i
猫巷女王i 2020-12-23 09:51

If i want severeal Column to make up an ID.

SQL example :

CONSTRAINT [PK_NAME] PRIMARY KEY ([Column1],[Column2],[Column3])

How can

相关标签:
5条回答
  • 2020-12-23 10:19

    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).

    0 讨论(0)
  • 2020-12-23 10:20
    1. Using @IdClass annotation on the @Entity class followed by @Id annotation on individual fields that are part of composite primary key.
    2. Alternatively can make use of @Embeddable class 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 @Embedded annotation in @Entity class. Hope this helps.
    0 讨论(0)
  • 2020-12-23 10:22

    You need to have a class for your composite key:

    public class CompositeKey implements Serializable {
        private int column1;
        private int column2;
        private int 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.

    0 讨论(0)
  • 2020-12-23 10:29

    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;
    }
    
    0 讨论(0)
  • 2020-12-23 10:31

    Use @Embeddable and @EmbeddedId.

    Example:

    @Entity
    public class Project {
        @EmbeddedId ProjectId id;
         :
    }
    
    @Embeddable
    Class ProjectId {
        int departmentId;
        long projectId;
    }
    

    More information here http://www.objectdb.com/java/jpa/entity/id#Embedded_Primary_Key_

    0 讨论(0)
提交回复
热议问题