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?
Don’t want to read? You can watch it here!
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!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.
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.
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.