2013-03-05 42 views
0

嗨,大家需要一些专家的意见。哪个更好(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; 
} 

此外,有没有什么我可以做些什么来改善我的代码?

回答

0

第二种方法是好的,但只有当你正在做一些事务性操作像添加,更新或删除。 你也不应该在POC的每个类中写入与事务有关的代码,或者测试这是好的。对于实际的生产代码,您应该在AOP(如果您使用的是Spring)中执行此操作,或者使用像添加,删除,获取等方法创建单独的类,例如HibernateGenericDAO。

+0

谢谢,我在回复跳转消息中提到,交易仅用于修复'没有活动交易得到无效':/ – Mercury 2013-03-05 19:31:37

+0

是的,你是对的。我不认为你需要提交交易。提交是DML所必需的。只读只读事务将用于从数据库读取数据。我已经提到第二种方法比第一种更好,因为代码对资源和异常有更好的处理。 – 2013-03-06 03:40:53

0

这里根本不需要交易。请记住,交易仅适用于DML。您不添加,修改或删除数据。你认为你可以回滚并提交什么?

您可以使用Session s = sessionFactory.openSession();避免 get是无效的无活动事务

+0

您提出了一个有效的观点,唯一的原因是它有一个错误:'没有活动事务得到是无效的' - 一直未能找到另一个修复程序 – Mercury 2013-03-05 19:25:29

+0

已更新答案 – hop 2013-03-05 19:43:48

+0

看起来我必须解决这个问题,很多关于getCurrentSession和openSession的争论 - 仍然不知道为什么开放会话将工作,而不是得到当前 – Mercury 2013-03-05 20:00:54