谁能帮我解决这个问题...
我创建了一个带有私有(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/