Scenario:
Consider a scenario where you need to store multiple versions of the same data entry, represented by id and Version columns. The goal is to create an entity that can duplicate entries with different versions.
Entity Definition:
To define an entity with a composite primary key, you can use the following approach:
<code class="java">@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 }</code>
<code class="java">@Entity public class YourEntity { @EmbeddedId private MyKey myKey; @Column(name = "ColumnA") private String columnA; // Getters and setters }</code>
Another Approach:
Alternatively, the @IdClass annotation can be used to define a composite primary key. This approach allows you to use the @Id annotation directly on the key fields.
<code class="java">@Entity @IdClass(MyKey.class) public class YourEntity { @Id private int id; @Id private int version; // Getters and setters }</code>
<code class="java">public class MyKey implements Serializable { private int id; private int version; // Getters and setters }</code>
Duplicating Entities:
To duplicate an entity with a different version, create a new instance with the same id but a different version value. This will create a separate entry in the database representing the new version.
The above is the detailed content of How to Implement Composite Primary Keys for Versioned Data Entries in JPA?. For more information, please follow other related articles on the PHP Chinese website!