Win a copy of The Little Book of Impediments (e-book only) this week in the Agile and Other Processes forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Hibernate Update Question

 
Abiodun Adisa
Ranch Hand
Posts: 495
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Lets Say i obtain an Object from the database using hibernate

String queryString = "from ApplicantResume";
Query queryObject = getSession().createQuery(queryString);
Man man=(Man)queryObject.list().get(0);

And after obtaining the Object lets say Man, and then i set one property of the object using a setter method,

man.setName("Testing");

How do i write the code to update this in the database
 
Mark Spritzler
ranger
Sheriff
Posts: 17278
6
IntelliJ IDE Mac Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Here is the thing you have



Where is the Session opened, when is it closed and the transaction commited?

Basically in Hibernate you open a Session, and start a transaction, you do some stuff, like in your case you query for a record then call a setter. At that point either session.flush() or committing the transaction(which flushes the session) will update the database. You do not need to call any special session.update(man) method to update that change.

Why, because you loaded it from the query within the session. Hibernate when loading the data will put a reference to the object into its PersistenceContext. It holds the object, the PersistenceContext holds many maps of your objects, including any dirty changes. So it knows you called the setter and that your object is dirty. Then when you flush, it goes through the dirty changes and flushes it to the database.

Most of the time this is just at time of commit, since a commit causes a flush, and this is the usual way to run things. You can manually call flush at anytime, but it is rare that you should do this.

Mark
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic