How to delete M2M relationship?

#1

In user model class I have the following:

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 timeslots = new HashSet();

And i would like to delete the timeslots..i've tried something but doesnt work, as follows:

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;
}
#2

Every entity object has to be removed by a separate invocation of the remove method. Removing a set of time slots in one invocation (as in your code) is not supported by JPA.

If Timeslot is the owner of the many-to-many relationship then the other side will be updated automatically when User instances are loaded again from the database (you can use clear or refresh to enforce update).

ObjectDB Support

Reply