开发者

How to execute sql-script file using hibernate?

开发者 https://www.devze.com 2022-12-16 06:42 出处:网络
I gonna write several intergration tests which will test interatcion with db. For ea开发者_开发百科ch test I need to have a certain snapshot of db. Each db snapshot saved in .sql file.

I gonna write several intergration tests which will test interatcion with db. For ea开发者_开发百科ch 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?


  • 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:

    @Transactional
    @TransactionConfiguration
    public class MyTest {
    ...
    }
    

If you don't use Spring, try a test framework with default-rollback transaction support.


The topic of deprecated Session.connection() method is dicussed here


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


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/

0

精彩评论

暂无评论...
验证码 换一张
取 消