hibernate insert to a collection causes a delete then all the items in the collection to be inserted again

后端 未结 7 1664
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-12-17 21:09

I have a many to may relationship CohortGroup and Employee. Any time I insert an Employee into the CohortGroup hibernate deletes the group from the resolution table and ins

相关标签:
7条回答
  • 2020-12-17 22:05

    Load the object in persistence context and call merge if exist and save if not exist.

    Employee emp = new Employee();
    //set emp attribute and members.
    Session session = ...
    Transaction transaction = ...
    Employee db = (Employee) session.get(Employee .class,emp.getId());
    if(db != null)  session.merge(emp);
    else  session.save(emp);
    /*session.saveOrUpdate(emp); This will delete the join table and reinsert entry  
    again*/
    transaction.commit();
    session.close();
    
    0 讨论(0)
提交回复
热议问题