【问题标题】:Spring @Transactional not working in few casesSpring @Transactional 在少数情况下不起作用
【发布时间】:2019-04-03 06:57:31
【问题描述】:

我的以下服务类用 @Transactional 注释。

@Service
@Transactional
public class MyService {

    @Autowired
    private SessionFactory sessionFactory;


    public Order acceptOrder(Order inputOrder) {
        Session session = sessionFactory.openSession();
        session.save(inputOrder);
        session.close();
        return inputOrder ;
    }

    public Order updateOrder(Order inputOrder) {

        Session session = sessionFactory.openSession();
        //session.beginTransaction();
        if(inputOrder.getOrderStatus().equals("confirmed")) {
            EmpAccount empAcc = (EmpAccount)session.get(EmpAccount.class, inputOrder.getEmpId());
            double newEmpBal = empAcc.getAvailable_balance() - inputOrder.getOrderAmount();
            empAcc.setAvailable_balance(newEmpBal);
            System.out.println("new bal"+newEmpBal);

            VendorAccount venAcc = (VendorAccount)session.get(VendorAccount.class,inputOrder.getvId());
            double newVenBal = venAcc.getBalance() + inputOrder.getOrderAmount();
            venAcc.setBalance(newVenBal);
            session.update(inputOrder);
        //  session.getTransaction().commit();
            session.close();
        }

        return inputOrder;
    } }

对于 acceptOrder()@Transactional 正在工作,我在 db 中创建了一个新行,但是当调用 updateOrder() 时,db 中没有任何变化。

谁能告诉我这是为什么? TIA

【问题讨论】:

  • 这两种情况都不起作用。将 Spring 与 Spring 托管事务一起使用时,切勿使用 openSession。而是使用getCurrentSession 并删除对session.close() 的调用。
  • 好的,现在可以工作了,谢谢,你能解释一下为什么当我打电话给acceptOrder()时你说它不起作用,因为我们也使用了openSession,它在数据库中进行了更新
  • 它做了一个插入,它在事务范围之外运行。它在范围之外运行,因为您正在获得与openSession 的非托管会话。它之所以有效,是因为它是插入而不是更新。

标签: spring hibernate spring-transactions transactional


【解决方案1】:

正如 M. Deinum 所评论的,对于 Spring 管理的事务,不需要打开和关闭 SessionSessionsessionFactory.getCurrentSession() 提供

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-04-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-10-18
    相关资源
    最近更新 更多