Home » Support » Forum » How to delete M2M relationship?

How to delete M2M relationship?


In user model class I have the following:

public class User implements Serializable {
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;

    @ManyToMany(mappedBy = "attendees", cascade = 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);

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


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

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
ObjectDB - Fast Object Database for Java (JPA/JDO)

Post Reply

To post a reply and/or subscribe to update notifications - please login