【问题标题】:After truncate with `.createSQLQuery` spring/hibernate does not rollback transaction使用 .createSQLQuery 截断后,spring/hibernate 不会回滚事务
【发布时间】:2017-09-11 15:42:36
【问题描述】:

我不明白为什么 Spring @Transactional 测试方法 Hibernate 不回滚在 @Before 中所做的更改?有information@Before@Test 在一个事务中被调用。可以考虑配置所有上下文。

@Test
@RunWith(SpringJUnit4ClassRunner.class)
@Transactional(defaultRollback = true, transactionManager = "transactionManager")
public class TestClass {

    @Autowired
    private SessionFactory sessionFactory;

    @Autowired
    private EntityDao entityDao;

    @Before
    public void before() {
        // create arbitrary entity
        Entity one = Utils.createEntity();
        // save with HibernateDao to table_1
        entityDao.save(one);
    }

    @Test
    public void test() {
        sessionFactory.getCurrentSession().createSQLQuery("TRUNCATE table_2").executeUpdate();
    }
}

如果没有createSQLQuery().executeUpdate@Before 中的所有更改都会根据需要回滚。

【问题讨论】:

标签: mysql spring hibernate junit transactions


【解决方案1】:

TRUNCATE Mysql 中的查询隐式提交事务(因为它被认为是 DDL 查询:它删除并重新创建表)。 DDL 查询通常会导致提交。

如果您需要一个交易行为良好的替代方案,您可以使用DELETE FROM <table-name>

更新

更多信息:Do DDL statements always give you an implicit commit, or can you get an implicit rollback?

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-02-06
    • 2011-02-19
    • 1970-01-01
    • 2016-11-03
    相关资源
    最近更新 更多