-1

I was looking for some real world scenarios for using hibernate / jpa methods

  1. like when to use merge() and when to use persist()?
  2. when to use getReference() vs find()?
  3. when do we require to detach the object? and what is the use of detaching the entity?
eatSleepCode
  • 4,427
  • 7
  • 44
  • 93

1 Answers1

1

Here are some examples:

  1. persist() should be used whenever you need to put a new object into database. Although merge() will persist the object if it doesn't exist, strange things have happened (to me, at least) in some corner cases when we used merge() for persisting new objects. One case where merge() is useful is when you first get the object from db, pass it to view/controller layer (or detach it in any other way), change it and you want to save the changes. With merge() this is done automatically, otherwise you would have to get the object from db by id and copy all the fields from the detached one (if you don't know precisely what changed).
  2. When you know the id of some entity object (either by having access to its detached copy, or some other way) which you just need to relate to another entity object. With getReference() you don't load the whole object into session, you only set it's reference into attached object so you end up having (at least) one query less then with find(). On the other hand, find() loads the whole object, no need to specify use cases for that.
  3. Although a DTO should be used for this example, imagine you have a web service returning an instance of your entity. And you don't want to return all of it's data, you want to null some attributes. If you do that on attached object, those nulls will be saved into database. So you detach it and modify it safely before returning it to the web service caller.
Predrag Maric
  • 23,938
  • 5
  • 52
  • 68
  • why merge creates a copy while persisting a transient entity? – eatSleepCode Sep 04 '15 at 10:00
  • [Here](http://spitballer.blogspot.rs/2010/04/jpa-persisting-vs-merging-entites.html) is a nice article about `merge` and `persist`, it should clear things up for you. – Predrag Maric Sep 04 '15 at 10:19
  • And a few more useful links: [link1](http://stackoverflow.com/questions/1069992/jpa-entitymanager-why-use-persist-over-merge) and [link2](http://techblog.bozho.net/how-does-merge-work-in-jpa-and-hibernate/) – Predrag Maric Sep 04 '15 at 10:23