BOSS_ladis
BOSS_ladis

Reputation: 49

How to use @GeneratedValue inside @Embeddable used as composite primary key?

I have in my data base one table with primary composite key, when I model it with Hibernate I use @EmbeddedId & @Embedable. One column of this composite primary key have a generated value with @GeneratedValue(strategy = GenerationType.IDENTITY).

When I try to create two new object in my data base I have an error like this :

org.hibernate.NonUniqueObjectException: A different object with the same identifier value was already associated with the session : [MyPackage#MyEmbedableClass [MyGeneratedPrimaryKeyValue=null, OtherPrimaryKey=21]]

But when I look in my data base my objects have been created. I don't understand my mistakes and I don't know how solve my problem.

I have found some topics like mine but I haven't found answer to my question.

  1. first exemple

  2. second exemple

  3. third exemple

@Entity(name = "Certification")
@Table(name = "CERTIFICATION")
public class Certification implements Serializable {

    static final long serialVersionUID = -4399907743392740963L;

    @EmbeddedId
    private CertificationPK certificationPK;

    // Others variables
    // constructors
    // Getter / Setter
    // toString
    // hashCode / equals
}

@Embeddable
public class CertificationPK implements Serializable {

    private static final long serialVersionUID = 1433990897506209802L;

    // MyGeneratedPrimaryKeyValue=null when I create
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @NotNull
    @Column(name = "CERTIFICATION_ID")
    private Integer certificationId; 

    // Other variable
    // constructors
    // Getter / Setter
    // toString
    // hashCode / equals
}

Thanks in advance for your help.

Upvotes: 4

Views: 3665

Answers (1)

SternK
SternK

Reputation: 13041

  1. It looks like you can not use @GeneratedValue with @EmbeddedId. You can find some workaround in this article but it did not work well for me.

  2. As it's stated in this section of documentation, it should be possible to use @GeneratedValue with @IdClass. But, it does not work due to HHH-9662.

  3. As it's stated in this section of documentation:

When using composite identifiers, the underlying identifier properties must be manually assigned by the user.

Automatically generated properties are not supported to be used to generate the value of an underlying property that makes the composite identifier.

Therefore, you cannot use any of the automatic property generator described by the generated properties section like @Generated, @CreationTimestamp or @ValueGenerationType or database-generated values.

Nevertheless, you can still generate the identifier properties prior to constructing the composite identifier.

Upvotes: 8

Related Questions