Search code examples
playframeworkmany-to-manyplayframework-2.0updatingebean

How to update a many to many relationship in Play framework 2 and ebean?


How do I update a many to many relationship in Play framework 2 and ebean? I keep getting errors like this:

[PersistenceException: org.postgresql.util.PSQLException: ERROR: duplicate key value violates unique constraint "pk_field_event" Detail: Key (field_id, event_id)=(3, 21) already exists.]

I'm trying to select which fields belong to an event using a form. I submit a form with a List of Fields. The id property is the only property that is populated. I then do the following:

Event event = Event.find(eventId);
event.fields = fieldsForm.get().fields;
event.update();

I've also tried loading each field from the db, adding the event to it, and then calling update() on the field.

Here are my classes:

Note: I removed Entity and Id annotations for simplicity.

public class Event {
    @ManyToMany(cascade = CascadeType.ALL, mappedBy = "events")
        public List<Field> fields;
    }
}

public class Field {
    @ManyToMany(cascade = CascadeType.ALL)
    public List<Event> events;
}

Solution

  • I'm not sure if this is the right way to do it, but it seems to do the trick. I just need to call updateFields():

    public static void removeField(Long eventId, Long fieldId) {
        Event event = Event.find.setId(eventId).fetch("fields").findUnique();
        event.fields.remove(Field.find.ref(String.valueOf(fieldId)));
        event.saveManyToManyAssociations("fields");
    }
    
    public static void updateFields(Long eventId, List<Field> fields) {
        Event event = find.setId(eventId).fetch("fields").findUnique();
    
        for(Field field : event.fields) {
            removeField(eventId, field.id);
        }
        for (Field field : fields) {
            if (field.id != null) {
                event.fields.add(Field.find.ref(String.valueOf(field.id)));
            }
        }
        event.saveManyToManyAssociations("fields");
    }