SQL JPA-多列作为主键 [英] SQL JPA - Multiple columns as primary key

查看:363
本文介绍了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.

这篇关于SQL JPA-多列作为主键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆