【问题标题】:Can it really be, that a transaction lasts longer than a session in hibernate?真的,事务持续时间比休眠中的会话长吗?
【发布时间】:2013-09-29 07:41:59
【问题描述】:

我有一个关于休眠的简单问题:

在休眠状态下,事务的持续时间真的比会话长吗?

@Controller
public class VacancyMenuController extends AbstractController{

...
   @RequestMapping("/path")
   public String delete(Model model){
  //here session opens and transaction starts ?
                 vacancyService.delete(vacancy.getId());
 //here transactions commit and session close ?

        sessionFactory.getCurrentSession().flush();

 //here session opens and transaction starts    ?
    Vacancy vacancyFromDb = vacancyService.findById(vacancy.getId());
//here transactions commit and session close    ?

        sessionFactory.getCurrentSession().flush();


    }
}

@TransactionConfiguration(defaultRollback = false)
    @ContextConfiguration(locations = { "classpath:/test/BeanConfig.xml" })
    public class AbstractServiceTest  extends AbstractTransactionalJUnit4SpringContextTests{
           ....
           @Test
        public void delete(){
//here session opens and transaction starts 
            vacancyService.delete(vacancy.getId());

            sessionFactory.getCurrentSession().flush();

            Vacancy vacancyFromDb = vacancyService.findById(vacancy.getId());   

            sessionFactory.getCurrentSession().flush();

            Assert.assertNull(vacancyFromDb);
//here transactions commit and session close
        }
}

在我的 cmets 上面的代码 sn-ps 是对的吗?

【问题讨论】:

    标签: java hibernate jpa orm


    【解决方案1】:

    Yes, exactly

    旨在在任何时候最多有一个与特定会话关联的未提交事务

    例子:

    From docs

    // BMT idiom
    Session sess = factory.openSession();
    Transaction tx = null;
    try {
        tx = sess.beginTransaction();
    
        // do some work
        ...
    
        tx.commit();
    }
    catch (RuntimeException e) {
        if (tx != null) tx.rollback();
        throw e; // or display error message
    }
    finally {
        sess.close();
    }
    

    您可以在此处找到被会话包围的事务。

    【讨论】:

    • 我猜这个例子中的事务比会话短。事务在会话打开后开始。并且事务在会话关闭之前已经关闭
    • @gstackoverflow 编辑了我的话。但是你在交易中完成了工作对吗??这意味着在提交事务之前。
    • 此顺序:1.session 打开 2.transaction sarts 3.transaction commits 4.session 关闭
    • 是的,是的。这样most one uncommitted Transaction associated with a particular Session at any time就满意了吧??
    • 问题是关于此顺序的可能性 //一些操作//事务开始后 //会话打开 //会话关闭 //事务提交
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-05-22
    • 1970-01-01
    • 1970-01-01
    • 2019-03-17
    • 1970-01-01
    • 2010-12-03
    相关资源
    最近更新 更多