2 回答
TA贡献1828条经验 获得超6个赞
我找到答案了,JPA的persist是调用Hibernate Session的persist方法进行持久化,persist会在事务提交或者有必要刷新缓存时才提交insert语句。
然而JPA的createNativeQuery就是直接调用本地数据库SQL语句,这个操作在Hibernate中是不算进事务中的。
所以persist的对象未被提交,后面执行的createNativeQuery方法,将不会看到前面要持久化的对象。
TA贡献1993条经验 获得超5个赞
参考:
The TestContext framework addresses this issue. By default, the framework will create and roll back a transaction for each test. You simply write code that can assume the existence of a transaction. If you call transactionally proxied objects in your tests, they will behave correctly, according to their transactional semantics. In addition, if test methods delete the contents of selected tables while running within a transaction, the transaction will roll back by default, and the database will return to its state prior to execution of the test. Transactional support is provided to your test class via a PlatformTransactionManager bean defined in the test's application context.
If you want a transaction to commit - unusual, but occasionally useful when you want a particular test to populate or modify the database - the TestContext framework can be instructed to cause the transaction to commit instead of roll back via the @TransactionConfiguration and @Rollback annotations.
添加回答
举报