spring hibernate transaction could not commit

10,997

You're using @Transactional, to have Spring start, commit and rollback transactions for you, and handle your transactions declaratively. The whole point of this is precisely to not have to start, commit and rollback transactions in the code. So the method implementation should simply be

return (List<Login>) sessionFactory.getCurrentSession().createQuery("from Login").list();
Share:
10,997
Aadam
Author by

Aadam

Updated on June 14, 2022

Comments

  • Aadam
    Aadam almost 2 years

    I wrote dao in spring as i used to write in struts some think like this

    @Autowired
        private SessionFactory sessionFactory;
        Session session=null;
        Transaction tx=null;
       List<Login> users= null;
        try{
            session=sessionFactory.getCurrentSession();
            tx=session.beginTransaction();
            users=session.createQuery("from Login").list();
            tx.commit();
        }catch(Exception e){System.out.println("commit exception:"+e);
            try {tx.rollback();} catch (Exception ex) {System.out.println("rollback exception:"+ex);} 
        }finally{if(session!=null && session.isOpen()){session.close();}}
    

    but i am getting this error:

    threw exception [Request processing failed; nested exception is org.springframework.transaction.TransactionSystemException: Could not commit Hibernate transaction; nested exception is org.hibernate.TransactionException: Transaction not successfully started] with root cause org.hibernate.TransactionException: Transaction not successfully started

    can someone please help me out.

    if i am writing it like this,

    try{
                users=sessionFactory.getCurrentSession().createQuery("from Login").list();
            }catch(Exception e){System.out.println("commit exception:"+e);
    

    its working fine, but is it safe?.

    Thanks and regards