How to create and handle composite primary key in JPA Ask Question

How to create and handle composite primary key in JPA Ask Question

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主キーになります。

エンティティはどのように見えるでしょうか? 別のバージョンで複製するにはどうすればよいでしょうか?

id Version ColumnA

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

ベストアンサー1

2 つのキーを含む を作成しEmbedded class、 のようにそのクラスへの参照を持つことEmbeddedIdができますEntity

必要なのは@EmbeddedIdそして@Embeddable注釈。

@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両方を配置することです。これで、両方の属性に通常の注釈を使用できます。idIdClass@Id

@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;
}

おすすめ記事