B) The problem I had to make forms for different elements. I had to fill the form (name, currency...), view it and modify it.However, while modifying the form, I had to be able to perform a classic undo (using a hit on my cancel button) and then retrieve the state of my country as it was before I began doing updates...C) The unsuccessful attempts and a first solution : I just have to say it was a pity for me to do that using JPA.
In the first case the entity is saved, in the latter case it is updated.
When switching from Hibernate to JPA a lot of people are dismayed to find that method missing. And figuring out what piece of code persisted (or merged or retrieved) that other entity is harder than figuring out why we get a "detached entity passed to persist" message.
To speed up the development we successfully use Hyper JAXB 3 ( which generates 90% of the code, though still need to handcraft some JPA annotations anyway. I see that Jeanne Boyarsky has already answered your question over at Code Ranch.
😉 But I'll answer your question for other readers of this blog: the difference is that a new entity is one that has just been created in Java but has not been persisted in the database yet, while a detached entity exists in Java I have a problem I'd like to tell you about : it's about jpa, entity, modification, undo (cancel modification)...
Apart from that latter consideration there is no need to invoke on an already persisted entity because any changes will automatically be saved at flush or commit time.
Those of you that have worked with plain Hibernate will probably have grown quite accustomed to using the method figures out whether the object is new or has already been saved before.
In fact I actually write separate DTO's for my more complex domain models and then you always have manually copy/merge the received data to your domain object. In our scenario the data comes from an external source in XML format (we use JAXB to unmarshal it), and needs to be merged with the one already in the DB. In fact, the major problem is the transfer protocol - the data is coming as a complex deeply nested XML (think of the complete invoice, including information about the customer), so the DIY merge is problematic.
We have chosen to specify the meaningful IDs in our entity beans and now it works completely transparently.
So let's examine the three possible cases and what the different methods do: I hope this blog gives you some pointers on how to save entities and how to work with detached entities. JDO 2.x uses the same method, Persistence Peristent(Object) for both persisting new objects and merging detached objects.
We'll get back to detached entities when we discuss Data Transfer Objects in a later blog. There is no distinction between persisting and attaching.
It all seems to work quite well until we run into the dreaded "detached entity passed to persist" message.