Search code examples
springhibernatespring-transactionstransactional

Spring @Transactional not working in few cases


I have my following service class annotated with @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;
    } }

For acceptOrder() , @Transactional is working and i have a new row created in db , but when updateOrder() is called no changes in db are reflected .

Can someone tell me why is this ? TIA


Solution

  • As commented by M. Deinum , for Spring managed Transactions , no need of opening and closing the Session , Session is provided by sessionFactory.getCurrentSession()