Spring Data JPA’s @PersistenceConstructor annotations are used with Hiberne?… here is a solution to the problem.
Spring Data JPA’s @PersistenceConstructor annotations are used with Hiberne?
I
want Hibernate to use another constructor instead of an empty constructor, because I have some logic that should be executed at object creation time but depends on object properties. I read here @PersistenceConstructor
solved this problem.
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 the instance from the database, I get the following exception:
org.hibernate.InstantiationException: No default constructor for entity
Did I do something wrong or did @PersistenceConstructor
comments not work in this case?
Solution
Spring Data @PersistenceConstructor
does not apply to JPA. It only applies to modules that do not use object mapping for the underlying data store.