users@glassfish.java.net

Re: jpa and object duplication/cloning

From: <glassfish_at_javadesktop.org>
Date: Tue, 08 Jan 2008 10:07:30 PST

Yea, ok, then you're pretty much stuck with the burden of cleaning up your object graph by hand and removing the primary keys. The JPA isn't going to do that for you.

There's a couple of mechanisms you could use to pull this off.

One, you could simply write several "reset" methods in all of your domain objects that take the responsibility of reseting the primary keys of the objects, and any child objects.

Another is to implement the Externalizable interface on all of your objects, set a flag in a global static (or thread local if that's what you need) that says "don't serialize the primary key", then write serialize the graph out to a ByteArrayStream, and then read it back in. This will readily handle the "graph" nature of your object, dealing with loops and sharing, and such. Otherwise you'd need to track and watch for recursive loops or whatever, depending on your graph complexity.

If it's truly a tree (with link back to parents, but basically a tree), then the "reset" method would be really efficient.

[code]
public void reset() {
    id = null;
    for(Child c : children) {
        c.reset();
    }
}
[/code]

If that won't send your graph in to an endless loop, then it's pretty simple, and easy to maintain.
[Message sent by forum member 'whartung' (whartung)]

http://forums.java.net/jive/thread.jspa?messageID=252774