如何在 JPA 中创建和处理复合主键 [英] How to create and handle composite primary key in JPA

查看:32
本文介绍了如何在 JPA 中创建和处理复合主键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想要来自同一数据条目的版本.换句话说,我想用另一个版本号复制条目.

I want to have versions from the same data entry. In other words, I want to duplicate the entry with another version number.

id - Version 将是主键.

实体应该是什么样子的?我怎样才能用另一个版本复制它?

How should the entity look like? How can I duplicate it with another version?

id Version ColumnA

1   0      Some data
1   1      Some Other data
2   0      Data 2. Entry
2   1      Data

推荐答案

您可以创建一个 Embedded class,其中包含您的两个键,然后将该类作为 EmbeddedId 的引用 在您的 Entity 中.

You can make an Embedded class, which contains your two keys, and then have a reference to that class as EmbeddedId in your Entity.

您需要 @EmbeddedId@Embeddable 注释.

You would need the @EmbeddedId and @Embeddable annotations.

@Entity
public class YourEntity {
    @EmbeddedId
    private MyKey myKey;

    @Column(name = "ColumnA")
    private String columnA;

    /** Your getters and setters **/
}

@Embeddable
public class MyKey implements Serializable {

    @Column(name = "Id", nullable = false)
    private int id;

    @Column(name = "Version", nullable = false)
    private int version;

    /** getters and setters **/
}

<小时>

实现此任务的另一种方法是使用 @IdClass 注释,并将您的 id 放在该 IdClass 中.现在您可以在两个属性上使用普通的 @Id 注释


Another way to achieve this task is to use @IdClass annotation, and place both your id in that IdClass. Now you can use normal @Id annotation on both the attributes

@Entity
@IdClass(MyKey.class)
public class YourEntity {
   @Id
   private int id;
   @Id
   private int version;

}

public class MyKey implements Serializable {
   private int id;
   private int version;
}

这篇关于如何在 JPA 中创建和处理复合主键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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