Question

I am using spring-data with hibernate. I have a bidirectional mapping as follow:

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;
   .....
}

When I delete student using the JpaRepository: repo.delete(s.getId()); I can see the following queries

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=?

Any idea why hibernate issue the 2 select queries? Is it not possible to just issue the delete queries without the selects?

Thanks

Was it helpful?

Solution

JPA only exposes a remove(…) method on EntityManager that takes the entity to be deleted. So for your call to delete(…) with the id we first check whether an entity with the id really existst (first query). We then materialize the object (second query) to eventually hand it to EntityManager.remove(…) (query 3 and 4).

Actually the exists(…) check is superfluous as we can simply check for null in the second step. I've created and fixed DATAJPA-363, so that you should see one query less in the future.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top