Win a copy of Machine Learning Systems: Designs that scale this week in the Scala forum
or Xamarin in Action: Creating native cross-platform mobile apps in the Android forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

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,

man.setName("Testing");

How do i write the code to update this in the database
 
ranger
Sheriff
Posts: 17314
11
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
 
my overalls have superpowers - they repel people who think fashion is important. Tiny ad:
Rocket Oven Kickstarter - from the trailboss
https://coderanch.com/t/695773/Rocket-Oven-Kickstarter-trailboss
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!