Saturday, August 2, 2014

Hibernate: How to update an Object

It's been a month since I'm dealing with Hibernate and apparently I really like the idea of having an OOP Database. But I have a little problem when trying to update an object (in SQL, you can simply use update syntax).

Hibernate have an update method but it's not as simple as we thought. Let say I have an object retrieved from the last session, and I already close the session. The transient object on the hibernate 'cache' has disappeared. It also means that the object you've retrieved has lost it's 'connection' to the data on the table. If somehow, after you do a lots of many things, you tried to update it again, you can't simply call the update() method. Hibernate can't find the proper data on the database anymore.

There is hard way to do it: use the objects id (primary key) to find the new object, update the object's values, and update it. It's too complicated. Luckily, you can use merge() to find the new data. So you can do this:

KRS krs = (KRS)session.merge(newKRS);

instead of doing the first method.

Hope it helps!

No comments: