2
votes

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

1
Why are you starting, committing and rollbacking transactions instead of letting Spring do it using AOP? My guess is that you're also doing it using Spring AOP, and that the programmatic transaction handling is interfering with Spring's own transaction handling. - JB Nizet
ya i have used @transactional in service. So is this the best way? - Aadam

1 Answers

3
votes

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();