简体   繁体   中英

Re-Attaching detached objects in Playframework

I have a process where a user can create an object (let's call it A) and manipulate it in several steps. The user can also add a reference to a persisted entity to the object (let's call the persisted entity B). I do not want to persist A in the database unless the last step has been finished, so I'm caching it after each step.

I am using Playframework with Java and JPA and so the B gets detached as soon as I retrieve it from the database, assign it to A and cache A. After submitting the last step, I need to have a transient object B again in order to persist it.

Here is the Exception

[PersistenceException: org.hibernate.PersistentObjectException: detached entity passed to persist: models.B]

What is the best way to archive that?

Thanks in advance

I'm a bit puzzled by your question. Entity objects will only be in detached state if they ever been managed by persistence context (eg: they ever been saved / updated / retrieved from database) or you create a new entity object and set its primary key field. Until then your entities are always transient. So looking at your requirement why not keep everything transient (eg: save it in http session) until the last step and persist everything ?

On a side note, if I'm not wrong the difference between detached and transient is the primary key field. So if you have a detached object and you reset the primary key field to default (0 or null) then you can say it's a transient entity. Under the hood maybe there's some object proxies leftover on a detached entity but not on transient, but I think it should not affect behavior:

// start transaction A..
User u1 = new User("Sam");  // u1 is transient
em.persist(u1);             // u1 is managed, say database gives us id 1
// commit and end transaction A..
em.detach(u1);              // u1 is detached

// start transaction B..
User u2 = new User("Sammy");// u2 is transient
u2.setId(1);                // u2 can be treated as detached object of u1 because it has same id
em.merge(u2);               // this should updates the user row with id 1 name from 'Sam' into 'Sammy'
// commit and end transaction B

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM