我在Servlet和Hibernate上编写项目。这是我的源代码示例:
@Override
public Long insertUser(User user) throws HibernateException {
Long id;
try{
session = sessionFactory.openSession();
session.beginTransaction();
id = (Long) session.save(user);
session.getTransaction().commit();
}finally{
if(session != null && session.isOpen())
session.close();
}
return id;
}
我有一个问题,我经常写相同的代码:
session = sessionFactory.openSession();
session.beginTransaction();
session.getTransaction().commit();
if(session != null && session.isOpen())
session.close();
我认为这很奇怪。你知道简化代码的解决方案吗?