java - Hibernate 允许私有(private)构造函数

标签 java hibernate jpa

谁能帮我解决这个问题...

我创建了一个带有私有(private)无参数构造函数的pojo(违背了JPA的建议,我们需要使用 protected 或公共(public)的构造函数) 我能够检索、更新、删除、插入数据。

为什么这是可能的?

@Entity @Table(name = "tb_pessoa")
public class Pessoa {

    @Id @GeneratedValue(strategy = GenerationType.AUTO)
    @Column(name = "pessoa_id")
    private Long id;

    @Column(name = "pessoa_nome")
    private String nome;

    private Pessoa() {}
}


@ExtendWith(DAOExtension.class)
public class PessoaDAOTest extends BaseDAOTest {

    @Test @SQL(scripts = {
        "scripts/inserir-joao.sql",
        "scripts/inserir-joao2.sql"
    })

    public void deve_consultar_pessoas_salvas() {
        List<Pessoa> pessoas = getEntityManager().createQuery("select p from Pessoa p").getResultList();
        Assertions.assertEquals(4, pessoas.size());

        Pessoa p1 = getEntityManager().find(Pessoa.class, 1 L);
        Assertions.assertNotNull(p1);
    }
}

最佳答案

根据Hibernate documentation (强调我的):

The entity class should have a no-argument constructor. Both Hibernate and JPA require this.

JPA requires that this constructor be defined as public or protected. Hibernate, for the most part, does not care about the constructor visibility, as long as the system SecurityManager allows overriding the visibility setting. That said, the constructor should be defined with at least package visibility if you wish to leverage runtime proxy generation.

关于java - Hibernate 允许私有(private)构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57095105/

相关文章:

Java数组递归

java - JPA/hibernate : "Missing Column" when joining columns

java - Spring Data 中的查询创建 - 动态 where 子句

java - udp 客户端/服务器中的未知主机异常

java - 使用 Android 从 HTML 代码解析 <form></form> 内的所有内容?

java - 在 ReSTLet 中向由 ClientResource 包装的请求添加 header

java - 移动到新的 spring 后无法启动服务器启动 Tomcat 上下文时出错

java - 我无法在代码中使用任何 ID

java - JPA 2.1、Hibernate 4.3、Spring 4.0 数据未保存到数据库

java - Spring Boot JPA ManyToMany 导致 OutOfMemoryError