hi all,
i've made an error thinking begin / commit transaction was unecessary in certain cases.
It seems many have done the same error.
To prevent this, i'd like to discuss about several cases.
I know this more a "db" knowledge but i think the forum can help much better.
the questions may look idiot but...
So i begin:
1- we see in the examples in the doc that it is a best practice to always use transaction even if we only make a "select", but is there a difference between:
1-a
sess = sf.openSession();
Transaction tx = sess.beginTransaction();
// execute some queries....
sess.find("from Cat as cat left outer join cat.kittens kitten");
....
tx.commit();
1-b
sess = sf.openSession();
// execute some queries....
sess.find("from Cat as cat left outer join cat.kittens kitten");
....
sess.connection.commit();
2- as it seems to be a best practice to always consider using connection.transaction, what about changing the servlet filter (open session in view
http://www.hibernate.org/43.html, modifications are in red
/**
*/
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException
{
if (hibernateHolder.get() != null)
throw new IllegalStateException(
"A session is already associated with this thread! "
+ "Someone must have called getSession() outside of the context "
+ "of a servlet request.");
try
{
chain.doFilter(request, response);
}
finally
{
Session sess = (Session)hibernateHolder.get();
if (sess != null)
{
hibernateHolder.set(null);
try
{
session.connection().commit(); // and in this case, what happens if a rollback() has occured before?
sess.close();
}
catch (HibernateException ex) { throw new ServletException(ex); }
}
}
}
/**
* ONLY ever call this method from within the context of a servlet request
* (specifically, one that has been associated with this filter). If you
* want a Hibernate session at some other time, call getSessionFactory()
* and open/close the session yourself.
*
* @return an appropriate Session object
*/
public static Session getSession() throws HibernateException
{
Session sess = (Session)hibernateHolder.get();
if (sess == null)
{
sess = factory.openSession();
hibernateHolder.set(sess);
}
session.beginTransaction();
return sess;
}
Thanks