使用Spring + Hibernate和事务注释.
我正在尝试测试以下内容:
@Transactional服务方法来持久化它我遇到的第一个问题是在步骤2中读取User对象,只返回Hibernate 1级缓存中的那个,并且实际上没有从数据库中读取.
因此,我使用Session手动从缓存中驱逐对象以强制从数据库读取.但是,当我这样做时,对象值永远不会在单元测试中持久存在(我知道在测试完成后它会因为我指定的设置而回滚).
我尝试在调用@Transactionalservice方法后手动刷新会话,并且DID提交更改.但是,这不是我的预期.我认为@Transactional服务方法可以确保事务已提交并且会话在返回之前刷新.我知道Spring一般会决定何时进行这种管理,但我认为方法中的"工作单元" @Transactional就是这种方法.
无论如何,现在我想弄清楚我将如何测试@Transactional一般的方法.
这是一个失败的junit测试方法:
@RunWith(SpringJUnit4ClassRunner.class)
@Transactional
@TransactionConfiguration(transactionManager = "userTransactionManager", defaultRollback = true)
@WebAppConfiguration()
@ContextConfiguration(locations = { "classpath:test-applicationContext.xml",
"classpath:test-spring-servlet.xml",
"classpath:test-applicationContext-security.xml" })
public class HibernateTest {
@Autowired
@Qualifier("userSessionFactory")
private SessionFactory sessionFactory;
@Autowired
private UserService userService;
@Autowired
private PaymentService paymentService;
@Autowired
private QueryService queryService;
@Autowired
private NodeService nodeService;
@Autowired
private UserUtils userUtils;
@Autowired
private UserContext userContext;
@Test
public void testTransactions() {
// read the user …Run Code Online (Sandbox Code Playgroud) spring hibernate sessionfactory transactional transactionmanager