Reputation: 33
I want Hibernate to use another constructor than an empty constructor since I have some logic that should be executed on object creation but depends on the object properties. I've read here that @PersistenceConstructor
solves this.
I created this example entity:
@Entity
public class TestEntity
{
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@JsonIgnore
public final Long id;
public final int width;
public final int height;
@Transient
private final double area;
@PersistenceConstructor
public TestEntity(Long id, int width, int height)
{
this.id = id;
this.width = width;
this.height = height;
this.area = width * height;
}
public double getArea()
{
return this.area;
}
public interface TestEntityRepository extends CrudRepository<TestEntity, Long>
{
}
}
However, when I try to retrieve an instance from the database, I get the following exception:
org.hibernate.InstantiationException: No default constructor for entity
Am I doing something wrong or does the @PersistenceConstructor
annotation not work in this context?
Upvotes: 3
Views: 7105
Reputation: 1050
Spring Data @PersistenceConstructor
does not work with JPA. It works only in modules that do not use the object mapping of the underlying data store.
Upvotes: 4