开发者

Hibernate - Update Operation:

开发者 https://www.devze.com 2023-03-13 04:35 出处:网络
@Entity @Table(name=开发者_JAVA百科\"Student\") public class Student { private String id; private String firstName;
@Entity
@Table(name=开发者_JAVA百科"Student")
public class Student {

    private String id;
    private String firstName;
    private String lastName;
    private Set<Grade> grades = new HashSet<Grade>();

public void addGrade(Grade grade){
        grades.add(grade);
    }
    //rest of Getters and setters omitted

    public void removeGrade(Grade grade){
    grades.remove(grade);
    }
@OneToMany(cascade = CascadeType.ALL,fetch=FetchType.LAZY,orphanRemoval=true)
    @JoinColumn(name="s_id")
    public Set<Grade> getGrades() {
        return grades;
    }

Grade:

@Entity
@Table(name="Grade")
public class Grade {
//all omitted
}

I have object student and I would like to remove one existing grade from the collection of graded on student with id 'xyz'

I'm doing the following:

String id = "xyz";
Session session = sessionFactory.getCurrentSession();
    Student student = (Student)session.load(Student.class,id);
        student.removeGrade(grade);
        session.update(student);

Everything works flawlessly , but in SQL queries, I see weird update:

Hibernate: select student0_.id as id0_0_, student0_.FirstName as FirstName0_0_, student0_.LASTNAME as LASTNAME0_0_ from Student student0_ where student0_.id=?
Hibernate: select grades0_.s_id as s4_0_1_, grades0_.id as id1_, grades0_.id as id1_0_, grades0_.FirstQuestion as FirstQue2_1_0_, grades0_.TotalGrade as TotalGrade1_0_ from Grade grades0_ where grades0_.s_id=?
Hibernate: update Grade set s_id=null where s_id=? and id=?
Hibernate: delete from Grade where id=?

Why do I have update? update Grade set s_id=null where s_id=? and id=?

How can I skip it, in order to increase performance?


It appears unnecessary, and it is in your case because your cascade type is ALL. However, there are some data models where it might make sense for the Child to be able to exist independently of being on the to-many relationship of another Entity. In other words, the update makes sense if you don't want to delete Grade if you break the relationship from Student to Grade. In that case, hibernate should just nullify the foreign-key value, but not delete the Grade row.

So this is what happens -- when you explicitly break the relationship by removing the child from the collection on the parent, hibernate knows to update the child table to remove the foreign key. When your cascade setting are set up with the 'ALL' setting (it actually is probably the orphanRemoval=true), hibernate knows to delete the actual child row when it no longer has a parent. I suspect that hibernate is not optimized such that it recognizes when it can just go to delete.

This was probably an optimization that they just chose not to implement.

You can read about collection performance here. Particularly section 19.5.

0

精彩评论

暂无评论...
验证码 换一张
取 消