如何删除JPA实体中的M2M对象?

时间:2013-08-06 19:26:33

标签: hibernate jpa jpql

在用户模型类中,我有以下内容:

public class User implements Serializable {
  @Id
  @GeneratedValue(strategy = GenerationType.AUTO)
  private Long id;
  @ManyToMany(mappedBy = "attendees", cascade = CascadeType.ALL)
  @Cascade(org.hibernate.annotations.CascadeType.ALL)
  private Set<Timeslot> timeslots = new HashSet<Timeslot>();
}

我想删除时段。我尝试了一些但不起作用,如下:

public static boolean deleteUserTimeslot(EntityManager em, Timeslot ts) {
        EntityTransaction transaction = em.getTransaction();
        try {
            ArrayList<User> attendeeList = (ArrayList<User>) ts.getAttendees();

            List<User> attendeesToRemove = (List<User>) getAllUsers(em);
            transaction.begin();

            for(User u: attendeesToRemove){
                for(int i=0;i<attendeeList.size();i++){
                    if(attendeeList.get(i).getId()==u.getId()){

                        em.remove(u.getTimeslots());
                        break;
                    }
                }        
            }
            transaction.commit();


            return true;
        } catch (PersistenceException ex) {
            //Rolling back data transactions
            if (transaction != null && transaction.isActive()) {
                transaction.rollback();
            }
            logger.error("Error making database call for update timeslot status");
            ex.printStackTrace();
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            e.printStackTrace();
        }
        return false;
    }

如何删除M2M实体?

1 个答案:

答案 0 :(得分:0)

你真的需要与会者成为List而不是Set吗?请参阅this

关于级联的两个观察结果:

  1. 有Cascade注释,删除其中一个(或两者)
  2. 不建议在ManyToMany关联中添加级联的documentation个州
  3.   

    在一个或多个上启用级联通常没有意义    协会。 Cascade通常很有用   和协会。

    在我看来,你想删除一个TimeSlot,对吧?如何删除TimeSlot和User之间的关系?

    // All attendees with this TimeSlot
    ArrayList<User> attendees = (ArrayList<User>) ts.getAttendees();
    // Bidirectional association, so let's update both sides of the relationship
    // Remove TimeSlot from Attendees
    for(User a : attendees){
        a.getTimeslots().remove(ts);
    }
    // Remove Attendees from TimeSlot
    ts.clear();
    // Save the changes
    em.merge(ts);
    em.remove(ts);