PersistenceConstructor

PersistenceConstructor

本文介绍了Spring Data JPA的@PersistenceConstructor注释是否可以与Hibernate结合使用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望Hibernate使用另一个构造器而不是空构造器,因为我有一些逻辑应在对象创建时执行,但取决于对象属性.我已阅读此处这个.

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

我做错什么了吗?还是@PersistenceConstructor注释在这种情况下不起作用?

Am I doing something wrong or does the @PersistenceConstructor annotation not work in this context?

推荐答案

Spring Data @PersistenceConstructor不适用于JPA.它仅在不使用基础数据存储的对象映射的模块中起作用.

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.

这篇关于Spring Data JPA的@PersistenceConstructor注释是否可以与Hibernate结合使用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-22 12:10