0

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

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 实体?

4

1 回答 1

0

您真的需要与会者成为列表而不是集合吗?看到这个

关于级联,我有两个观察结果:

  1. 有级联注释,删除其中之一(或两者)
  2. 文档指出不建议在 ManyToMany 关联中添加 Cascade

在 a or 关联上启用级联通常没有意义。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);
于 2013-08-07T04:25:30.970 回答