Hibernate Tips: How to create a database setup script based on entity mappings

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.

Question:

I want to use a database setup script instead of Hibernate’s schema generation. What’s the easiest way to create this script for an existing entity model?

Solution:

JPA 2.1 introduced a schema generation features which can setup your database or export the generated commands to a file. You just have to set the following configuration parameters in your persistence.xml file to activate it:

javax.persistence.schema-generation.scripts.action
Defines which scripts the persistence provider shall create. You can choose between none, create, drop-and-create, drop.
A script target needs to be defined for each script to be created.

javax.persistence.schema-generation.scripts.create-target
Defines the target location of the create script generated by the persistence provider as a file URL or a java.IO.Writer.

javax.persistence.schema-generation.scripts.drop-target
Defines the target location of the drop script generated by the persistence provider as a file URL or a java.IO.Writer.

Here you can see a persistence.xml configuration that generates a create and a drop script based on the entity mapping information.

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.