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 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?
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:
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.
Defines the target location of the create script generated by the persistence provider as a file URL or a java.IO.Writer.
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!I've created a printable PDF for this Hibernate Tip. As always, you can download it for free from the Thoughts on Java Library.
You can use JPA’s schema generation feature also to setup and initialize databases based on the entity mapping information or a set of SQL scripts. I explain it in more detail in my post Standardized schema generation and data loading with JPA 2.1.