How to populate your DB with sample data during Hibernate bootstrap?


One of the undocumented features of Hibernate is its execution of SQL scripts given within a special file during bootstrap. It is a very useful feature in order to populate your DB with sample data during testing or development mode. If you create a file named import.sql under project’s root classpath, and put SQL statements within it, Hibernate is going to execute those statements right after schema export operation.

However, you need to be aware of one or two things while you are using import.sql. First is that, SQL statements you put into that file might be DB specific, therefore you need to replace its contents whenever you change your target DB. Second is that, in order for Hibernate to process this file, its property value should be either “create” or “create-drop“.

As you know, we are a big fun of Spring Application Framework, and I want to mention about an alternative but much more flexible way provided by Spring for such sample data population requirements. By using jdbc:embedded-database or jdbc:initialize-database JDBC namespace elements, it’s very easy to load sample data not only in application scope, but also specific to each individual test class in your project as well.



As we always say that, using Hibernate with Spring in your projects makes things much easier on Hibernate side, and you will become much more productive compared to using Hibernate alone.