2

I know there are a lot of discussions about this famous detached entity passed to persist error. I met that error. I well linked my entities, but that wasn't the problem: I was linking an entity to an already existing one. I tried merge() instead of persist(), which well executed the transaction. I enquired for that merge() method, and I learnt here and there the main point: it copies the state of the passed object. Right.

My question is, instead of

em.persist(e); e.anything();

is it a bad idea to use

e = em.merge(e); e.anything();

?

If I well understood, merge() returns the managed instance that the state was merged to, which should mean that overwriting the given entity with the returned one gives access to the persistent entity, doesn't it?

I saw that "solution" nowhere, so I'm asking. Mea culpa if it's a duplicated question :)

Community
  • 1
  • 1
sp00m
  • 44,266
  • 23
  • 127
  • 230

1 Answers1

1

is it a bad idea to use e = em.merge(e); e.anything();

Whether or not this is a bad idea depends upon your application and what you are doing before the merge and what you are doing in anything().

A merge will fix the 'detached entity' error in certain cases. In other cases, it'll satisfy entity manager's requirements while breaking your application.

To answer the question for your specific case, you'll have to ask yourself: Where is e coming from? What does it contain? Does it have a relationship to other entities? If so are these relations bidirectional? etc...

beerbajay
  • 17,345
  • 6
  • 52
  • 72