Problem with Hibernate template
I use hibernate for save, update and delete data in my database, but I have some problems.
For example I have a request for 开发者_如何学运维save or update my data in database
getHibernateTemplate().saveOrUpdate(client);
getHibernateTemplate().flush();
When I launch my server (TomCat) for the first and I save my data, all is okay, in my database I see my data.
If I delete the data and I run a new save of my client, it performs an Update rather than an Insert even though I have deleted the data.
That's because the objects are in memory already and hibernate already persisted them. When the application starts, hiberante loads the objects in memory as they are needed (lazy fetching) if not defined otherwise. When an object changes programatically, hibernate persists the object to the database. You don't need to use save()
, just commit()
. save
is just for new created objects, and update()
is for re-attaching detached objects to a session.
You can't change the database data without using hibernate and expect hibernate to realize that the database changed. You must change the data using hibernate session
methods.
If you change the data not using hibernate and you want hibernate to reaload the object, use the session.refresh()
method to reload the object into memory from the database. This way the changes in the database will be reflected in the object loaded in memory.
More info in Chapter 10 of Hibernate documentation
精彩评论