其实我正在寻找在hibernate 4.2.x中使用session和DAO的最佳实践
第一种方法:
public class AccountDAOImpl implements AccountDAO {
Session session=HibernateSessionFactoryUtil.getSession();
Transaction transaction =null;
@Override
public void saveAccnt(Account account) {
// TODO Auto-generated method stub
try
{
transaction=session.beginTransaction();
session.save(account);
transaction.commit();
}
catch(RuntimeException re)
{
if(transaction!=null)
transaction.rollback();
throw re;
}
finally
{
session.close();
}
}
}
或我们采取第二种方法:
public class AccountDAOImpl implements AccountDAO {
Session session=HibernateSessionFactoryUtil.getSession();
Transaction transaction =null;
@Override
public void saveAccnt(Account account) {
// TODO Auto-generated method stub
try
{
transaction=session.beginTransaction();
session.save(account);
transaction.commit();
}
catch(RuntimeException re)
{
if(transaction!=null)
transaction.rollback();
throw re;
}
}
}
每次需要执行DAO的关闭会话中的实际差异需要在工作完成时关闭会话。
已更新:
public class HibernateSessionFactoryUtil {
private static SessionFactory sessionFactory=null;
public static Session getSession() {
if(sessionFactory==null)
{
createSessionFactory();
}
return sessionFactory.openSession();
}
public static SessionFactory getSessionFactory() {
if(sessionFactory==null)
{
createSessionFactory();
}
return sessionFactory;
}
private static void createSessionFactory() {
Configuration configuration = new Configuration();
configuration.configure("/hibernate.cfg.xml");
ServiceRegistry serviceRegistry = new ServiceRegistryBuilder().applySettings(configuration.getProperties()).buildServiceRegistry();
sessionFactory = configuration.buildSessionFactory(serviceRegistry);
}
}
答案 0 :(得分:1)
你不应该用你的方法关闭会话:你没有在那里打开它。
做第二种方法,或者这样做:
public class AccountDAOImpl implements AccountDAO {
@Override
public void saveAccnt(Account account) {
Transaction transaction =null;
Session session=HibernateSessionFactoryUtil.getSession();
try
{
transaction=session.beginTransaction();
session.save(account);
transaction.commit();
}
catch(RuntimeException re)
{
if(transaction!=null)
transaction.rollback();
throw re;
}
finally
{
session.close();
}
}
}