嗨,大家需要一些专家的意见。哪个更好(1或2),为什么?
1 - 无交易对象休眠获取方法代码审查
public Car getCar(long ID){
Session s = sessionFactory.getCurrentSession();
s.beginTransaction();
Car c = (Car) s.get(Car.class, ID);
s.getTranscaction().commit();
return c;
}
2 -
public Car getCar(long ID)
{
Session s = sessionFactory.getCurrentSession();
Transaction t = null;
Car c = new Car();
try
{
t = s.beginTransaction();
c = (Car) s.get(Car.class, ID);
t.commit();
} catch (Exception e)
{
e.printStackTrace();
if (t != null)
t.rollback();
} finally {
if(s.isOpen())
s.close();
}
return c;
}
此外,有没有什么我可以做些什么来改善我的代码?
谢谢,我在回复跳转消息中提到,交易仅用于修复'没有活动交易得到无效':/ – Mercury 2013-03-05 19:31:37
是的,你是对的。我不认为你需要提交交易。提交是DML所必需的。只读只读事务将用于从数据库读取数据。我已经提到第二种方法比第一种更好,因为代码对资源和异常有更好的处理。 – 2013-03-06 03:40:53