<img alt="" src="https://secure.leadforensics.com/150446.png " style="display:none;">
Go to top icon

Using Composite Id in Hibernate 4.2.1.Final

Madhura Oak Jun 25, 2013

Hibernate 4.2.1.Final hibernate Hibernate 3.5 @EmbeddedId @Id @Embeddable Technology Composite Id

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

Similar Blog

e-Zest is a leading digital innovation partner for enterprises and technology companies that utilizes emerging technologies for creating engaging customers experiences. Being a customer-focused and technology-driven company, it always helps clients in crafting holistic business value for their software development efforts. It offers software development and consulting services for cloud computing, enterprise mobility, big data and analytics, user experience and digital commerce.