Embedable & Reference?

#1

Hi!

I've got a situation I do not understand. Assume code like this:

@Embedable
public class EmbeddedThing
{
    private String name;

    public String getName() ..
    public void setName(String name)..
}

@Entity
public class TopLevelClass
{
    private EmbeddedThing thing;
    private List<EmbeddedThing> things;

    public void addThing(EmbeddedThing thing)
    {
        things.add(thing);
        this.thing = thing;
    }

    public EmbeddedThing getFirstEmbeddedThing()
    {
        return things.get(0);
    }
}

Now I create an instance of TopLevelClass and add a new Instance of EmbeddedThing to it.
Works okay. Now what I do is to modify the newly added thing by calling something like getFirstEmbeddedThing().setName("Yeah"). However, after comitting, the entry in the things-list is correctly updated with the name but the referencing "thing" property in the TopLevelClass does still keep the old name why??

I was under the impression that they both point to the same instance or is it that when assigning this.thing = thing they are actually different embedded objects after retrieving from the db?

Does this also mean that referencing an already embedded object will save it twice in the db?

If so, how can I achieve in what I want besides using a separate Entity class instead of my Embedded class?

thanks!

Alex

#2

This is the normal behavior. Embedded objects cannot be shared by multiple references.

If you have multiple references to an embedded object during persist then multiple instances of that embedded object are stored in the database and later each one of them is retrieved and managed separately.

This is one of the consequences of not having an identity for embedded objects.

Sharing persistent objects is only possible with entity objects.

ObjectDB Support

Reply