在用户模型类中,我有以下内容:
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 实体?