I have a method which delete some items, and next insert some others items.
public void refresh() {
if (newitems != null) {
toto.clear();
for (totoDao p : newItems) {
toto.store(p);
}
}
newitems = null;
}
public void clear() {
final Session session = this.getHibernateUtil().getSession();
int n = session.createQuery(DELETE).executeUpdate();
session.clear();
session.flush();
}
public void store(TotoDao object) {
final Session session = this.getHibernateUtil().getSession();
session.saveOrUpdate(object);
session.flush();
}
For the moment I have one flush in clear() method and other one in store() method.
I want to add all of theses stuffs in one “transaction”, if somethings appears, a application restart just after the toto.clear(), for example, i want that transaction rollback all the block.
So what are the best solution for perfomances and persistances ?
Thx !
Just enclose these two method calls inside a unique transaction.
Flushing doesn’t have anything to do with transactions. It just means “really execute all the SQL statements needed to persist the modifications made in the session”. But the commit will only be done at the end of the transaction.
Flushing the session manually is almost always unnecessary. Let Hibernate do it when it has to.
Also, note that a DAO is supposed to be a service object allowing to query and update entities. It’s not supposed to be a persistent entity.
Read http://docs.jboss.org/hibernate/core/3.6/reference/en-US/html_single/#transactions and http://docs.jboss.org/hibernate/core/3.6/reference/en-US/html_single/#objectstate-flushing