开发者

Hibernate collection removal after flush

The collection data is removed from the database after a session flush. It seems Hibernate detected the original collection is replaced, but in our legacy project, we don't want Hibernate to do the removal. Is there any way to do it?

Below is the sample code:

public class Student{
    @OneToMany(fetch=FetchType.EAGER)
    @JoinColumn(name="student_id")
    private List<Course> courses;
    ......

    public static void main(String[] args){
        SessionFactory sessionFactory = HibernateUtil.getSessionFactory();
        Session session = sessionFactory.openSession();
        session.beginTransaction();

        Student s = (Student) session.get(Student.class, id);
        //set new name
        s.setName("new name");

        // this is neccessary in our project, and I can't change it.
        List<Course> newCourses = new ArrayList<Course>();
        newCourses.add(...);
        s.setCourses(newCourses);  // replace the collection with new

        //update s
        session.update(s);

        session.getTransaction().commit();
        session.clo开发者_如何学Gose();
    }
}

After a transaction commit, Hibernate will remove the collection data in the database, because the original collection is replaced with a new one, but I don't want Hibernate to do this. Is there any way to do it?


It means that you only want to add some courses for a student. So you should only add the new courses to the student's exisitng courses list instead of replacing it with a new list:

List newCourses = new ArrayList();
newCourses.add(...);

/*** Add a list of new course instead of replacing with a new list***/
s.addCourse(newCourses);

addCourse(List courseList) is a method of the Student which will add all elements of the input list courseList to the student's internal courses list.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜