Mohammed Falha
Mohammed Falha

Reputation: 967

How to persist Entity twice JPA

I have an entity, that represent order sent by the customer , this order might be updated after some discussion with the customer on phone, but the initial order sent by the customer must be persisted without update. how i can persist same entity twice , is it efficient to use deep cloning. i have tried to detach the the entity in order for persistence context to persist a new one , but still the persistence context is updating the first entry.

Upvotes: 0

Views: 2010

Answers (3)

James
James

Reputation: 18389

You need to clone/copy the object, ensure it has a unique id (or null if generated).

In EclipseLink there is an API to copy objects,

http://wiki.eclipse.org/EclipseLink/Examples/JPA/AttributeGroup#Copy_Examples

Upvotes: 0

Smertokogt
Smertokogt

Reputation: 201

You can not persist one object twice in one session, so you need copy your order and save (persist) it again. hibernate copy object values into new object with new generated ID

Upvotes: 2

wobblycogs
wobblycogs

Reputation: 4093

That's an interesting question. I think the quickest solution would probably be to use a multi-part ID. The first part would be the original order number and then every change increments the second part of the key. In your code you'd just need to find the object, make sure it's detached, alter the second part of the key and then persist it. As long as it's been detached it should then be saved away as a new order.

This post shows you how to use a composite key.

Upvotes: 0

Related Questions