java - Spring + Hibernate + JPA 在 JUnitTest 时, 不发出insert语句

 W布二 发布于 2022-10-28 18:17

单元的测试方法为:

@Test
@Transactional(propagation=Propagation.REQUIRED)
@Rollback
public void test() {
    userCreateService.saveUsers(2392L, "@abc.com", true, "A", new Long[]{129L, 1L, 2L, 131L, 4L}, 5);
}

设置了事务, 进入了方法里面, 调用javax.persistence.EntityManager.persist()方法都是不提交insert语句.

发个例子说明一下:

我想要插入一个user到数据库, 然后立刻把他的OPENID字段使用Oracle的sys_guid()函数来生成, 所以persist后, 调用本地查询语句来修改.
发现修改语句一直说修改了0个结果, 我查了一下Hibernate的SQL语句输出, 发现没有发出过insert语句. 这是为何呢?

请各位大神帮忙...............

2 个回答
  • 参考:

    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.

    2022-10-29 20:41 回答
  • 我找到答案了,JPA的persist是调用Hibernate Session的persist方法进行持久化,persist会在事务提交或者有必要刷新缓存时才提交insert语句。
    然而JPA的createNativeQuery就是直接调用本地数据库SQL语句,这个操作在Hibernate中是不算进事务中的。
    所以persist的对象未被提交,后面执行的createNativeQuery方法,将不会看到前面要持久化的对象。
    2022-10-29 20:41 回答
撰写答案
今天,你开发时遇到什么问题呢?
立即提问
热门标签
PHP1.CN | 中国最专业的PHP中文社区 | PNG素材下载 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有