gpt4 book ai didi

hibernate - JPA 2.0/Hibernate - 为什么 hibernate 在删除之前发出选择计数 (*) 查询

转载 作者:行者123 更新时间:2023-12-02 03:46:29 24 4
gpt4 key购买 nike

我在 hibernate 中使用 spring-data。我有一个双向映射如下:

public class Student {
...
@OneToMany(fetch = FetchType.EAGER, cascade = CascadeType.ALL, orphanRemoval = true, mappedBy="student")
private List<StudentLog> logs = newArrayList();
...
}

public class StudentLog {
.....
@ManyToOne(cascade = CascadeType.REFRESH, optional = false, fetch = FetchType.LAZY)
@JoinColumn(name = "STUDENT_ID" , insertable = true, updatable = false, nullable =false)
private Student student;
.....
}

当我使用 JpaRepository 删除学生时:repo.delete(s.getId());我可以看到以下查询

Hibernate: select count(*) as col_0_0_ from STUDENTS student0_ where student0_.ID=? and 1=1
Hibernate: select student0_.ID as ID1_2_2_, student0_.FIRST_NAME as FIRST2_2_2_, educationh1_.STUDENT_ID as STUDENT6_2_4_, educationh1_.ID as ID1_0_4_, educationh1_.ID as ID1_0_0_, educationh1_.CLASS as CLASS2_0_0_, educationh1_.LEVEL as LEVEL3_0_0_, educationh1_.PREDICTED_END_DATE as PREDICTE4_0_0_, educationh1_.START_DATE as START5_0_0_, educationh1_.STUDENT_ID as STUDENT6_0_0_, educationh1_.TERM as TERM7_0_0_, logs2_.STUDENT_ID as STUDENT3_2_5_, logs2_.ID as ID1_3_5_, logs2_.ID as ID1_3_1_, logs2_.LOG as LOG2_3_1_, logs2_.STUDENT_ID as STUDENT3_3_1_ from STUDENTS student0_ left outer join EDUCATION_HISTORY educationh1_ on student0_.ID=educationh1_.STUDENT_ID left outer join STUDENT_LOG logs2_ on student0_.ID=logs2_.STUDENT_ID where student0_.ID=?
Hibernate: delete from STUDENT_LOG where ID=?
Hibernate: delete from STUDENTS where ID=?

知道为什么 hibernate 会发出 2 个选择查询吗?没有选择就只发出删除查询是不可能的吗?

谢谢

最佳答案

JPA 仅在 EntityManager 上公开了一个 remove(…) 方法,该方法接受要删除的实体。因此,对于使用 id 调用 delete(...),我们首先检查具有该 id 的实体是否真的存在(第一个查询)。然后我们具体化对象(第二个查询),最终将其交给 EntityManager.remove(…)(查询 3 和 4)。

实际上 exists(…) 检查是多余的,因为我们可以在第二步中简单地检查 null。我已经创建并修复了 DATAJPA-363 ,这样您以后就应该少看到一个查询。

关于hibernate - JPA 2.0/Hibernate - 为什么 hibernate 在删除之前发出选择计数 (*) 查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16639267/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com