Creating and Handling Composite Primary Keys in JPA
When managing data that requires versioning, it is often necessary to create a composite primary key consisting of an identifier and a version number. This enables the creation of duplicate entries with different versions.
To implement this scenario in JPA, there are two primary approaches: using an Embedded class and using the @IdClass annotation.
Method 1: Embedded Class
Example:
<code class="java">@Entity public class YourEntity { @EmbeddedId private MyKey myKey; @Column(name = "ColumnA") private String columnA; // 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 }</code>
Method 2: @IdClass Annotation
Example:
<code class="java">@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; }</code>
Both of these approaches allow for the creation and handling of composite primary keys in JPA, enabling the management of data with multiple versions or duplicates.
The above is the detailed content of How to Create and Handle Composite Primary Keys with Versioning in JPA?. For more information, please follow other related articles on the PHP Chinese website!