I have a table which contains only 2 fields. The table has a composite PK formed by these two fields.
When using Netbeans for creating entity beans from database, the entity bean is not created automatically like other tables that have more than 2 fields.
So I guess I need to create the entity bean myself. What is the best practice for creating this entity bean? Does it have to contain COMPOSITE KEY object or not?
I don’t use NetBeans so I can’t really say anything about its mapping tools.
For mapping a composite key, there are a couple of options. You can
Define a separate
@Embeddableobject with the PK fields and use it as@EmbeddedIdin your@EntityclassDefine a non-mapped POJO with the PK fields and use it as
@IdClassin the@Entity.In this example
ClassABIdis a static inner class just for convenience.These options are also explained in Pascal Thivent’s excellent answer to this question: How to map a composite key with Hibernate?.
This related question discusses differences between these approaches: Which anotation should I use: @IdClass or @EmbeddedId. Notice the fields’ declaration gets duplicated with the
@IdClassapproach.Anyhow, I don’t think there’s an alternative to creating two classes. That’s why I asked this question : Mapping a class that consists only of a composite PK without @IdClass or @EmbeddedId. It seems there’s an hibernate-specific feature for this.
As a side note, if you’ve got control over the DB structure, you might also consider avoiding composite keys. There are some reasons to do so.