• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
  • Liutauras Vilda
  • Campbell Ritchie
  • Tim Cooke
  • Bear Bibeault
  • Devaka Cooray
  • Jeanne Boyarsky
  • Knute Snortum
  • Junilu Lacar
Saloon Keepers:
  • Tim Moores
  • Ganesh Patekar
  • Stephan van Hulst
  • Pete Letkeman
  • Carey Brown
  • Tim Holloway
  • Ron McLeod
  • Vijitha Kumara

Hibernate Update Question  RSS feed

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,


How do i write the code to update this in the database
Posts: 17314
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.

It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!