Search |
||
Using Composite Keys with JPAPosted by bleonard on November 29, 2006 at 9:14 AM PST
The Java Persistence API is beautiful. I create a class, annotate it with @Entity and @Id and I'm on my way. That is, however, assuming the Id is of a simple type (I'm a firm believer that primary keys should be of a simple type, unrelated to the data they index.). However, if you find yourself in a situation where you must use a composite key (hopefully this is only because you're connecting to some existing data set), JPA will still work for you, although it gets a bit more complex. First of all, you can declare a composite primary key using one of two annotations: @IdClass or @EmbeddedId. In this blog, I'm going to focus on the latter. Using @EmbeddedIdA composite primary key must be represented by a primary key class. And when using the @EmbeddedId approach, it must be annotated as @Embeddable. @Embeddable public class ContactPK implements Serializable { @Column(name = "FIRSTNAME", nullable = false) private String firstname; @Column(name = "LASTNAME", nullable = false) private String lastname; ... The primary key in the entity class is annoated with @EmbeddedId annotation: @Entity public class Contact implements Serializable { /** * EmbeddedId primary key field */ @EmbeddedId protected ContactPK contactPK; ... However, it doesn't stop there. The entity class must also implement the hashcode() and equals() methods. As I mentioned in my introduction, hopefully you're only using composite keys if you already have existing tables defined that way. In the spirit of that assumption, we're going to start with a table and just use NetBeans to create our entity class. Setting Things UpTo continue we need NetBeans 5.5 and the Java EE Application Server 9.0. If you need both, just download and install the bundle. Creating the TableCompositeCustomer.sql will create a table with a composite primary key populated with some sample data.
Generating Entities With Composite KeysThe setup was the hard part. To create the entity class:
And you're done. The wizard created the primary key class, CompositeCustomerPK as well as the entity CompositeCustomer. Testing the EntityHere we'll delete our table and let JPA re-create it for us.
»
Related Topics >>
J2EE Comments
Comments are listed in date ascending order (oldest first)
|
||
|
|