SQL JPA-多列作为主键

问题描述:

如果我想让严重列组成ID.

If i want severeal Column to make up an ID.

SQL示例:

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

如何使用Jpa Entity类来做到这一点?通过columndefinition吗?

How can i do that with a Jpa Entity class ? through columndefinition ?

只需将id字段设置为:

just setting the id field as:

value = Column1 + Column2 + Column3 // aint working.

您需要为复合键提供一个类:

You need to have a class for your composite key:

public class CompositeKey implements Serializable {
    private int column1;
    private int column2;
    private int column3;
}

,然后在您的实体类中使用@IdClass批注:

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!

是的,还有另一种解决方案,@jklee提到的解决方案都可行,这是优先选择的问题.

Yea and there is the other solution, the one that @jklee mentioned, both work, it's a matter of preference.