3

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.

Jens Schauder
  • 77,657
  • 34
  • 181
  • 348
Sidd
  • 41
  • 4
  • 1
    Use Float as PK is not good idea, my first though. and the error probably is something like. An ancestor of this class (Derived) has already defined the primary key. The ID class may not be defined here. – Koitoer Feb 01 '14 at 06:50

1 Answers1

1

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;

}
Prasanna
  • 131
  • 1
  • 11