SQL JPA - Multiple columns as primary key

前端 未结 5 1378
猫巷女王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: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.

提交回复
热议问题