As says on To initialize or not initialize JPA relationship mappings? is good practice to initialize the relations on JPA mapping.
But into web architecture (Spring MVC), where the entities will be send as JSON, usually with a RESTfull API, the relations will be omitted on the serialization and it will be fetched to the server using its path (i.e employees/[id]/projects).
If we have:
class Employee {
@ManyToMany //Employee owner of relation
protected List<Project> projects=new ArrayList<Project>(0);
}
If from the client we want to update only the Employee name, the client send the JSON to the server (HTTP PUT), it is deserialized and employee.projects will be initialized as empty collection. When the EntityManager save, it will update the properties (right) and the projects (Employee is owner side) DELETING the existing projects.
A alternative is use the DIY merge pattern. "Instead of invoking EntityManager.merge we invoke EntityManager.find to find the existing entity and copy over the state ourselves". This workaround requires specific entity code on update.
What is the best way to solve it?