3

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?

Hovercraft
  • 33
  • 1
  • 6
  • Since `@PersistenceConstructor` is apparently a "Spring Data JPA" annotation then it safe to assume that Hibernate will NOT "support" it, since it supports the JPA API –  Aug 28 '18 at 13:57
  • Ok so I guess the question should be 'Does Spring Data JPA's @PersistenceConstructor annotation work in combination with hibernate?' – Hovercraft Aug 28 '18 at 14:09
  • As far as I can tell, PersistenceConstructor has no effect with JPA/Hibernate persistence (because JPA/Hibernate persistence always want a default constructor, and use setter to set properties). PersistenceConstructor is only useful with noSql Spring-data persistence flavor : MongoDb, etc. – Zartc Sep 23 '18 at 17:55
  • Then it makes sense why @PersistenceConstructor exists, maybe Hibernate makes it work in the future. Thanks! – Hovercraft Sep 25 '18 at 20:36

1 Answers1

4

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.

psmagin
  • 1,000
  • 2
  • 9
  • 17