Using composite Id with auto-generated values
If you are planning to use an entity with composite Id in Hibernate as shown in Listing 1, then you cannot auto-generate values of @Id
using @GeneratedValue(strategy=GenerationType.IDENTITY)
.
If you attempt to do so then you’ll get the following exception:
java.lang.IllegalArgumentException: Can not set java.lang.Long field somepackage.StatementId.sequence to org.hibernate.id.IdentifierGeneratorHelper$2
This is a bug in Hibernate HHH-064 which also exists in version 4.2.1.Final
The work around is to explicitly generate @Id value within your Java code instead of using auto-generated value.
@Entity
@IdClass(StatementId.class)
public class Statement {
@Id
@ManyToOne
private Document document;
@Id
private Long sequence;
...
}
Listing 1. An entity with composite Id
Using @EmbeddedId
Using @EmbeddedId
as shown in Listing 2 does not work in Hibernate 4.2.1 though it works in Hibernate 3.5.x.
It gives the following exception in Hibernate 4.2.1.Final:
org.hibernate.annotations.common.AssertionFailure: Declaring class is not found in the inheritance state hierarchy: somepackage.StatementId
The workaround for this is to use @IdClass
instead of @EmbeddedId
.
@Embeddable
public class StatementId implements Serializable {
@Id
@ManyToOne
private Document document;
@Id
private Long sequence;
/* getters and setters */
}
@Entity
public class Statement {
@EmbeddedId
private StatementId id;
...
}
Listing 2. Using @EmbeddedId
in entity