你需要将事务范围扩展到测试方法的范围。你可以通过将测试方法(或整个测试类)注释为
@Transactional:
@Test @Transactionalpublic void testInsert(){ long id=myService.addPerson("JUNIT"); assertNotNull(id); if(id<1){ fail(); } } 你还可以使用这种方法来确保在回滚之前正确写入了数据:
@Autowired SessionFactory sf;@Test @Transactionalpublic void testInsert(){ myService.addPerson("JUNIT"); sf.getCurrentSession().flush(); sf.getCurrentSession().doWork( ... check database state ... ); } 


