I need to create a composite key. One attribute of the key is in a MappedSuperClass which I cannot modify. The other attribute of the key is in the derived class which is an entity class. However, I get a runtime error on executing the below which says that the attribute of the base class(which is also present in @IdClass), is not an attribute of the Entity class(the Derived class). Please guide me on how to handle this situation.

@MappedSuperClass
public abstract class Base
{
    @Id
    protected String id;
}

@Entity
@Idclass(DerivedPK.class)
public Derived extends Base
{
    @Id
    protected float version;
}

public class DerivedPK
{
    private String id;
    private float version;
}

I get an error saying attribute "id" present in DerivedPK is not found in class "Derived". Hibernate version used is 4.1.1.Final.

1

There are 1 answers

0
Prasanna On

This can be achieved using the below-mentioned example code.

Do not forget to make use of logical names (baseProp, childProp) instead of physical (base_prop, child_prop) once.

@Data and @EqualsAndHashCode(callSuper = true) these are lombok provided annotations which reduce the overhead of writing getters and setters for all the entity properties.

Example:

@Data
@MappedSuperclass
public class BaseEntity {

  protected Long baseProp;

}

@Data
@Entity
@EqualsAndHashCode(callSuper = true)
@Table(uniqueConstraints = {
    @UniqueConstraint(columnNames = {"baseProp", "childProp"})
})
public class ChildEntity extends BaseEntity {

@Id
private Long id;

private String childProp;

}