Take the 2-minute tour ×

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:

public void test_stuff(){

   ... testing logic ...


Does hibernate has some means to do this?

share|improve this question

4 Answers 4

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

    public class MyTest {

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

share|improve this answer
Rod Johnson talks about using transactions and rollback for doing integration testing: infoq.com/presentations/system-integration-testing-with-spring You can skip to the 30 minute mark if you're already familiar with the reasons for testing. –  0sumgain Jan 19 '10 at 3:20
Interesting but a bit old: the author speask about testing with AbstractTransactionnal... test classe, which is now deprecated in spring 3.0.0 in Favor of @Transactionnal annotation (and it's a much better way). –  Kartoch Jan 19 '10 at 19:37
@Kartoch hoping you still get this: I tried your solution but no luck, is still valid in hibernate 4? –  jorrebor Nov 20 '12 at 15:10
@jorrbor what is not working ? –  Kartoch Nov 20 '12 at 15:58

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

share|improve this answer
I'm sorry but... how is this relevant to the question? –  Pascal Thivent Oct 6 '10 at 7:13
When trying to retrieve JDBC connection to execute your sql script, the first thing you'll notice is that the method is deprecated, but there's not alternative recommended way to retrieve it. –  Rots Oct 8 '10 at 8:47

You can get hold of the underlying JDBC connection via the hibernate session instance:


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.


share|improve this answer

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/

share|improve this answer
alternative for in-memory database: h2 (h2database.com) –  Kartoch Mar 20 '12 at 18:22

Your Answer


