如何使用hibernate执行sql脚本文件?
我将编写几个集成测试来测试与数据库的交互。 对于每个测试,我需要有一个特定的数据库快照。每个数据库快照保存在 .sql 文件中。 我想要的是在某些测试方法中执行某些脚本文件,如下所示:
@Test
public void test_stuff(){
executeScript(finame.sql);
... testing logic ...
clean_database();
}
Hibernate 有一些方法可以做到这一点吗?
I gonna write several intergration tests which will test interatcion with db.
For each test I need to have a certain snapshot of db. Each db snapshot saved in .sql file.
What I want is to execute certain script file in certain test method, like this:
@Test
public void test_stuff(){
executeScript(finame.sql);
... testing logic ...
clean_database();
}
Does hibernate has some means to do this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您可以在 hibernate 启动时自动执行 SQL 脚本:将 SQL 命令写入名为 import.sql 的文件中,并将其放在 CLASSPATH 的根目录中。
您不需要为测试清理数据库,只需将测试设置为事务性的,并在每次测试结束时进行回滚即可。因此,您确信您的数据库没有被测试污染。例如,使用 Spring:
<前><代码>@Transactional
@事务配置
公共类我的测试{
...
}
如果您不使用 Spring,请尝试使用默认回滚事务支持的测试框架。
You can automatically execute SQL script at startup of hibernate: write your SQL commands in a file called import.sql and put it in the root of the CLASSPATH.
You don't need to clean your database for your test, just make your test as transactional with rollback at the end of each test. Hence, you are sure your database is not contaminated by your tests. For instance, using Spring:
If you don't use Spring, try a test framework with default-rollback transaction support.
此处讨论了已弃用的 Session.connection() 方法的主题
The topic of deprecated Session.connection() method is dicussed here
您可以通过 hibernate 会话实例获取底层 JDBC 连接:
https://www.hibernate.org/hib_docs/v3/api/org/hibernate/Session.html#connection()
您可以编写executeScript()方法来获取文件名和hibernate会话并读取文件并在jdbc连接上执行sql。
华泰
You can get hold of the underlying JDBC connection via the hibernate session instance:
https://www.hibernate.org/hib_docs/v3/api/org/hibernate/Session.html#connection()
So you could write your executeScript() method to take the filename and a hibernate session and read the file and execute the sql on the jdbc connection.
HTH
您听说过 Hypersonic SQL 吗?它是一个内存数据库,所有表都驻留在内存中,然后进行测试(使用读取、更新、插入、删除),最后当您关闭时,所有数据都消失了。了解更多信息:http://www.hsqldb.org/
Have you heard of Hypersonic SQL? It's an in-memory database where all your tables reside in the memory, then do your test (with Read, update, insert, delete), finally when you close, all data is gone. Read more at: http://www.hsqldb.org/