What is the difference between a session and a transaction in JPA 2.0?

前端 未结 4 1783
终归单人心
终归单人心 2020-12-23 11:30

I just begin my JPA 2.0 studies, and I have this piece of code:

em = SessionFactory.startSession();
tx = em.getTransaction();

My problem is

4条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-23 11:46

    In Hibernate, the transaction management is quite standard, just remember any exceptions thrown by Hibernate are FATAL, you have to roll back the transaction and close the current session immediately.

    Here’s a Hibernate transaction template :

        Session session = null;
        Transaction tx = null;
    
        try{
            session = HibernateUtil.getSessionFactory().openSession();
            tx = session.beginTransaction();
            tx.setTimeout(5);
    
            //doSomething(session);
    
            tx.commit();
    
    
        }catch(RuntimeException e){
            try{
                tx.rollback();
            }catch(RuntimeException rbe){
                log.error("Couldn’t roll back transaction", rbe);
            }
            throw e;
        }finally{
            if(session!=null){
                session.close();
            }
        }
    

提交回复
热议问题