In this particular case I need to create a shallow copy. I am developing
web application with standard CRUD operations for every table / entity
class. I was looking for a way to add "duplicate" action.
To sum things up, I tried to:
1. Find entity, change primary key field (int) to 0, and persist.
Result: "Attempt to change a primary key field of an instance that
already has a final object id. Only new, unflushed instances whose id
you have not retrieved can have their primary keys changed."
2. Find entity, clone(), change primary key field to 0, and persist.
Result: "ERROR: null value in column "id_some_foreign_key" violates
not-null constraint (...)"
3. Find entity, BeanUtils.copyProperties, change primary key field to 0,
persist. This seems to work.
4. Find entity, serialize, deserialize, change primary key field to 0,
persist, as Henno suggested. This also seems to work, but I have some
issues with lazy loaded objects.
5. Of course, copy constructor is always an option, but it takes a bit
more work.
Regards,
Ognjen
On 14.1.2011 15:52, Henno Vermeulen wrote:
The easiest way that I found to create a deep clone of an object graph is to
use apache commons collections.
SerializationUtils.deserialize(SerializationUtils.serialize(object)).
Can of course also be used for a simple entity without relations. In anyway you
have to watch out that you still set all primary keys to null. (May also not be
most performant way.)
Regards,
Henno Vermeulen
Huize Molenaar
-----Oorspronkelijk bericht-----
Van: Ognjen Blagojevic [mailto:[email protected]]
Verzonden: vrijdag 14 januari 2011 15:12
Aan: [email protected]
Onderwerp: How to persist duplicate of an entity?
Hi,
Is there an easy way to create duplicate of an entity?
I want to read entity from the DB, and then persist (almost) identical
copy. Every field should be the same, except primary key.
I know I could probably use BeanUtils.copyProperties, but is there
OpenJPA preffered way to do the duplication?
Regards,
Ognjen