When the business layer creates a new entity, which logically represents an instance of an existing entity that should be updated (say they share the same business key), is this method of merging bad practice?
public User add(User user){
User existingUser = getUserDao().findByBusinessKey(user.getBusinessKey(), false);
user.setId(existingUser.getId());
user = getUserDao().merge(user);
return user;
}
I ask because setting the ID explicitly on the detached entity feels pretty strange to me, but even though the equals and hashcode method of the User entity are appropriately implemented, setting the ID here is the only way to ensure the merge takes place.
Is there a better practice?
Are there specific drawbacks to this method that would bite me later on?
Thanks for taking a look!
That code will work, but setting the ID explicitly on the detached entity should not be necessary. A typical Hibernate app have a 'save' method that handles two cases:
Looks like something in your code isn't doing the second case in the typical way. If the 'user' object comes from some prior Hibernate query (triggered by the user clicking 'edit user' or something like that), then it will already have an ID. Thus, only the merge(user)
call is needed.
I usually do something like this:
if (user.getId() == null)
em.persist(user);
else
user = em.merge(user);
Then I add code to handle optimistic locking issues (another session updated the object) and unique constraint issues (another session tried to persist something with the same business key).
Frameworks such as Seam can make this even simpler because they propagate the Hibernate session between the controller bean methods. So even the 'merge' is not needed.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With