Hibernate Tips is a series of posts in which I describe a quick and easy solution for common Hibernate questions. If you have a question you like me to answer, please leave a comment below.
I need to create a database and initialize it with a set of test data. Is there an easy way to do that with Hibernate?
Don’t want to read? You can watch it here!
Hibernate implements the JPA standard which defines a set of configuration parameters to setup a database. The following code snippet shows an example of such a configuration in the persistence.xml file.
OK, this configuration might look overwhelming at the beginning, but it’s pretty simple and flexible as soon as you know the different parameters.
It tells Hibernate to use 2 SQL scripts to drop an existing database, to create a new and to run an SQL script afterward to initialize it. Let’s have a look at the different configuration parameters:
- persistence.schema-generation.database.action = drop-and-create tells Hibernate to first drop and then create a new database,
- persistence.schema-generation.create-source = script and javax.persistence.schema-generation.drop-source = script define that Hibernate shall use a script to create and drop the database and
- persistence.schema-generation.create-script-source and javax.persistence.schema-generation.drop-script-source specify the location of these scripts and
- persistence.sql-load-script-source provides the path the to the SQL script which Hibernate shall use to initialize the database.
As you have seen, the configuration isn’t too complicated. The parameters follow an easy to understand the concept, and they provide the required flexibility to create a configuration that fits your application.
Get this Hibernate Tip as a printable PDF!Join the free Thoughts on Java Library to get access to lots of member-only content, like a printable PDF for this post, lots of cheat sheets and 2 ebooks about Hibernate.
These are not the only parameters you can use to create and initialize your database. I explained all of them in the post: Standardized schema generation and data loading with JPA 2.1.
Hibernate Tips Book
It gives you more than 70 ready-to-use recipes for topics like basic and advanced mappings, logging, Java 8 support, caching and statically and dynamically defined queries.
Get it now as a paperback, ebook or PDF.