Nimchip
Nimchip

Reputation: 1735

Entity as key on a One to One relationship returning "Composite-ID" error

I have the following 2 entities:

   @Entity(name = "Employee")
   @Table(name = "EMPLOYEE")
   public class Employee implements Serializable {
      @Id
      @Column(name = "EMP_ID", insertable = true, updatable = false, nullable = false)
      private int id;

and

@Entity(name = "Draw")
@Table(name = "DRAW")

public class Draw extends AuditableEntity {
    @Id
    @OneToOne(fetch = FetchType.LAZY, cascade = {CascadeType.PERSIST, CascadeType.MERGE})
    @JoinColumn(name = "EMP_ID", referencedColumnName = "EMP_ID")
    @Cascade({org.hibernate.annotations.CascadeType.SAVE_UPDATE,
        org.hibernate.annotations.CascadeType.MERGE})
    private Employee employee = null;

Let's just say that's the way they want it modeled. This is a OneToOne relationship as specified. However, when I go to test I get the following error:

nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'sessionFactory' defined in class path resource [META-INF/spring/datasource-context.xml]: Invocation of init method failed; nested exception is org.hibernate.MappingException: composite-id class must implement Serializable: com.myprojects.tet.data.entity.Draw

Why is the employee key in Draw interpreted as a composite-id? Also how do I fix this error. I have read that the entity referenced has to be serializable but also that it needs to implement method equals and hashCode (which I haven't implemented yet). Should implementation of those two fix that error?

Editing for clarity:

I have two modeled tables: EMPLOYEE and DRAW:

EMPLOYEE has: integer emp_id, plus a lot of other columns.

DRAW has: integer emp_id, integer totalPoints.

The draw table will be populated and purged every certain time, so column totalPoint cannot be in table EMPLOYEE. I am unsure if my entity relations are correct (i.e. having entity employee as the id for draw).

Upvotes: 1

Views: 1795

Answers (1)

Tomasz Nurkiewicz
Tomasz Nurkiewicz

Reputation: 340743

Replace @JoinColumn with @PrimaryKeyJoinColumn:

@Id
@Column(name = "EMP_ID")
private int id;

@OneToOne(fetch = FetchType.LAZY, cascade = {CascadeType.PERSIST, CascadeType.MERGE})
@PrimaryKeyJoinColumn(name = "EMP_ID", referencedColumnName = "EMP_ID")
@Cascade({org.hibernate.annotations.CascadeType.SAVE_UPDATE, org.hibernate.annotations.CascadeType.MERGE})
private Employee employee;

Upvotes: 3

Related Questions