用休眠方式截断所有表的最佳方法? [英] Best way to truncate all tables with hibernate?

查看:51
本文介绍了用休眠方式截断所有表的最佳方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想截断一次集成测试到另一次集成测试之间的所有数据库表.使用休眠模式执行此操作的最佳方法是什么?

I would like to truncate all my database tables between one integration test to another. What is the best way to do this using hibernate?

目前我正在这样做:

public void cleanDatabase() {
        doWithSession(new Action1<Session>() {
            @Override
            public void doSomething(Session session) {
                SQLQuery query = session.createSQLQuery("truncate table stuff");
                // todo - generify this to all tables
                query.executeUpdate();
            }
        });

(doWithSession是一个小的包装器,用于创建和关闭会话).我可以使用反射对所有映射对象进行迭代...我想知道是否有人已经解决了这个问题.

(doWithSession is a small wrapper that creates and closes a session). I could iterate on all my mapped objects using reflection ... I'm wondering if someone already solved this problem.

推荐答案

我想您可能不使用Spring.如果您这样做了,请 Spring的事务测试支持将是理想的选择.

I guess you probably don't use Spring. If you did, Spring's transactional test support would be ideal.

简而言之:Spring在每个测试用例之前自动启动一个事务,并在测试用例之后自动将其回滚,从而为您留下一个空的(或至少未更改的)数据库.

In short: Spring automatically starts a transaction before each test case and automatically rolls it back after the test case, leaving you with an empty (or at least unchanged) database.

也许您可以模仿这种机制:

Perhaps you could just mimic that mechanism:

使用 @Before 方法打开事务,然后使用 @After 方法将其回滚.

Open a transaction in a @Before method, roll it back in an @After method.

这篇关于用休眠方式截断所有表的最佳方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆