I want to persist my EMF model in such a way to avoid duplicating objects unnecessarily. To do so I'm trying to use cross-references, but it throws an Exception saying that the reference is not contained in a resource.
For example, let's consider a Company and its CEO. There are two scenarios for calls of
company1.setCEO(ceo1);
company2.setCEO(ceo1);
1- when containment is set to true, only the last company stores the reference to the ceo; 2- when containment is set to false, the exception is thrown.
How do I fix this?
In the EMF, container references must have an upper bound of 1. In your case that means ceo1 can be contained in only one company. That's why your first scenario ends with only the second company storing the reference to the ceo.
In the second case, the problem seems to be also a containment issue. If you are using non-containment reference between company and CEO, you have to define in wich object your CEO is contained. The simplest way to do that is to add it to the resource content
resource.getContents().add(ceo1)
. But a better design solution would add a containment reference to CEO in the class it belongs to.