Hi
I'm using Hibernate version 2.1.2, MySQL version 4.0.18
I have a question regarding long transactions using session.disconnect() and session.reconnect(). Is it dangerous to simply make a method that returns the session in a disconnected state, and whenever I make a connection to the DB I reconnect, do what I want, and then diconnect like this:
//+ imports;
public class UserService
{
public User getUser(String userName)throws HibernateException
{
User user = null;
Session session = HibernateUtilities.currentSession();
session.reconnect();
String hql="from people.Person as user where" + "userName='"+userName+"'";
List list = session.find(hql);
for(Iterator iter = list.iterator();iter.hasNext();)
{
user = (User)iter.next();
}
session.disconnect();
return user;
}end getUser
public void saveOrUpdateToDatabase(Object object) throws HibernateException
{
Session session;
Transaction transaction = null;
try {
session = HibernateUtilities.currentSession();
session.reconnect();
transaction = session.beginTransaction();
session.saveOrUpdate(object);
transaction.commit();
session.disconnect();
} catch (HibernateException e) {
if(transaction!=null)
transaction.rollback();
e.printStackTrace();
}
} // end saveToDatabase
}
//+imports
public class HibernateUtilities {
private static final SessionFactory sessionFactory;
static {
try {
sessionFactory = new Configuration()
.configure().buildSessionFactory();
} catch (HibernateException ex) {
throw new RuntimeException(
"Exception building SessionFactory: " + ex.getMessage(), ex);
}
}
public static final ThreadLocal local = new ThreadLocal();
//Returns a disconnected Session object
public static Session currentSession() throws HibernateException {
Session session = (Session) local.get();
if (session == null) {
session = sessionFactory.openSession();
session.disconnect();
local.set(session);
}
return session;
}
public static void closeSession() throws HibernateException {
Session session = (Session) local.get();
session.reconnect();
local.set(null);
if (session != null)
session.close();
}
}
I experience no problem doing it like this, but i wonder if it is not the most efficent way around.. Also I'm not sure if it is ok to load an object from a database lik I do in getUser(String userName), work with it an its lazy collections, and then update it in DB using the method saveOrUpdateToDatabase(Object object)..
--dag--
|