在Java中用JPA组成的主键

时间:2017-06-21 08:14:53

标签: java jpa primary-key

是否有一个解决方案来声明一个主键,该主键由Java中的JPA两个字段组成?

例如:

@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;

@Id
private String identity;

主键是(id,identity)。

2 个答案:

答案 0 :(得分:1)

是的,您可以使用@IdClass注释指定一个类,该类将被称为组合键。

例如:

@Table('myTable')
@IdClass(ComposedKey.class)
public class myEntity {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;

    @Id
    private String identity;

    private String otherFields;

}

public class ComposedKey implements Serializable {
    private long id;
    private String identity;

    //Getter / Setter

}

然后,您的密钥将是ComposedKey

答案 1 :(得分:0)

是的,有几种方法可以实现这一目标。很容易在www。

中找到这个答案

看看这个:http://www.objectdb.com/java/jpa/entity/id#Composite_Primary_Key_

电贺。

[UPDATE]

我更喜欢使用嵌入式PK:

@Embeddable
public class ClassPK implements Serializable {
    @Basic(optional = false)
    @NotNull
    @Size(min = 1, max = 145)
    @Column(nullable = false, length = 145)
    private String idOne;
    @Basic(optional = false)
    @NotNull
    @Column(nullable = false)
    private Integer idTwo;
    @Basic(optional = false)
    @NotNull
    @Size(min = 1, max = 145)
    @Column(nullable = false, length = 145)
    private String idThree;

然后在实体中:

@Entity
@Table(catalog = "", schema = "")
public class Entity implements Serializable {

    @EmbeddedId
    protected ClassPK classPK ;

    @Column(name = "date")
    @Temporal(TemporalType.DATE)
    private Date date;
    @Column(name = "realTime", precision = 22)
    private Double realTime;
    @Size(max = 150)
    @Column(name = "cnc", length = 150)
    private String cnc;

正如您在Id类中看到的,您可以拥有任意数量的字段(在我的情况下,我有3个字段的复合PK)。

在实体中,您可以定义所有其他列。