0

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

真的,事务持续时间比休眠中的会话长吗?

@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
        }
}

在我的评论上方的代码片段中是对的吗?

4

1 回答 1

0

Yes, exactly

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

例子:

来自文档

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

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

于 2013-09-29T07:44:32.507 回答