Reputation: 16351
I'm fairly new to Hibernate and JPA, and am currently working on an application that uses it through JPA's EntityManager.
When looking at some basic hibernate tutorials using Hibernate session, I see that I can do :
val session = HibernateUtil.getSessionFactory().getCurrentSession()
session.beginTransaction()
val coordinates = session.find(Coordinates::class.java, "12345")
coordinates.longitude = 0.0
session.save(coordinates)
session.getTransaction().commit()
When using Entitymanager, it's done this way :
val em = emFactory.createEntityManager()
em.transaction.begin()
val coordinates = em.find(Coordinates::class.java, "12345")
coordinates.longitude = 0.0
em.transaction.commit()
The main difference here is that using EntityManager, I don't have to explicitly make a call to a save
function to actually update the object, which will be flushed eventually during commit. Of course, I coul do something like
if(obj.id == null) {
return em.merge()
} else {
val saved = em.persist(obj)
return saved
}
But what's the point for already existing objects if they get saved anyway, no matter if I call this or not ?
Surprisingly, the examples found around here seem to rely on a save method as well.
My question is : is there a way to configure EntityManager to update the objects only when requested specifically (i.e. mimick session behavior) ? Or do I have to use Session to achieve this ?
Upvotes: 0
Views: 2147
Reputation: 118744
merge
is the opportunity for the EntityManager to actually perform database operations. Merging, persisting, flushing, and committing are essentially all contact points with the database.
For simple cases, you can simply rely on changing the behavior at commit and not physically merge yourself, but many like the control knowing when it will actually happen. Knowing that "after this, it's in the DB". Because after the merge, not only is the data persisted, along with any cascading behavior, but also any side effects from triggers etc. on the DB have happened as well.
They're not committed, but they've happened. Keys are assigned for parents and children, triggers have fired, lifecycle methods have fired, everything is "as it should be", "right now", vs "sometime in the future" even if that may only be milliseconds away.
Upvotes: 1