Bozhidar Bozhanov

About Bozhidar Bozhanov

Senior Java developer, one of the top stackoverflow users, fluent with Java and Java technology stacks - Spring, JPA, JavaEE. Founder and creator of Computoser and Welshare. Worked on Ericsson projects, Bulgarian e-government projects and large-scale online recruitment platforms.

Schema Creation Script With Hibernate 4, JPA And Maven

The scenario is trivial – you want to generate a database schema creation script while building your application (and then execute the script on the target database) This was relatively easy with Hibernate 3, as there was the hibernate3-maven-plugin, but it is not compatible with Hibernate 4. And for every new project you should start with Hibernate 4, of course. So what to do? It’s relatively simple, but takes some time to research and test. The idea is to use the SchemaExport tool. But it’s a bit tricky, because it only supports native Hibernate configuration and not JPA.

First, you create a command-line application that handles the export. Note that Ejb3Configuration is deprecated, but it is deprecated for external use – hibernate are using it internally quite a lot. So it is a properly working class:

@SuppressWarnings('deprecation')
public class JpaSchemaExport {

 public static void main(String[] args) throws IOException {
  execute(args[0], args[1], Boolean.parseBoolean(args[2]), Boolean.parseBoolean(args[3]));
 }

 public static void execute(String persistenceUnitName, String destination, boolean create, boolean format) {
  System.out.println('Starting schema export');
  Ejb3Configuration cfg = new Ejb3Configuration().configure(persistenceUnitName, new Properties());
  Configuration hbmcfg = cfg.getHibernateConfiguration();
  SchemaExport schemaExport = new SchemaExport(hbmcfg);
  schemaExport.setOutputFile(destination);
  schemaExport.setFormat(format);
  schemaExport.execute(true, false, false, create);
  System.out.println('Schema exported to ' + destination);
 }
}

Note here, that we are not directly deploying the file to the target database. (the 2nd argument to .execute is false). This is because we don’t have our database connection properties in persistence.xml – they are external. Deploying the schema file is done later in the maven build, but this is beyond the scope of this post.

Then we have to just invoke this class from the maven build. I initially tried creating it as an ant task and run it with the antrun plugin, but it has classpath and classloader problems (doesn’t find the entities and persistence.xml). That’s why I used the exec-maven-plugin, which invokes the application in the same JVM as the build is running:

<plugin>
 <groupId>org.codehaus.mojo</groupId>
 <artifactId>exec-maven-plugin</artifactId>
 <version>1.1</version>
 <executions>
  <execution>
   <phase>${sql.generation.phase}</phase> <!-- this is process-classes in our case currently -->
   <goals>
    <goal>java</goal>
   </goals>
  </execution>
 </executions>
 <configuration>
  <mainClass>com.yourcompany.util.JpaSchemaExport</mainClass>
  <arguments>
   <argument>core</argument>
   <argument>${project.build.directory}/classes/schema.sql</argument>
   <argument>true</argument>
   <argument>true</argument>
  </arguments>
 </configuration>
</plugin>

Then you can use the sql-maven-plugin to deploy the schema.sql file to the target database (you will need to have the externalized db properties loaded by maven, which is done by the properties-maven-plugin).

Reference: How To Generate A Schema Creation Script With Hibernate 4, JPA And Maven from our JCG partner Bozhidar Bozhanov at the Bozho’s tech blog blog.

Related Whitepaper:

Functional Programming in Java: Harnessing the Power of Java 8 Lambda Expressions

Get ready to program in a whole new way!

Functional Programming in Java will help you quickly get on top of the new, essential Java 8 language features and the functional style that will change and improve your code. This short, targeted book will help you make the paradigm shift from the old imperative way to a less error-prone, more elegant, and concise coding style that’s also a breeze to parallelize. You’ll explore the syntax and semantics of lambda expressions, method and constructor references, and functional interfaces. You’ll design and write applications better using the new standards in Java 8 and the JDK.

Get it Now!  

Leave a Reply


3 + six =



Java Code Geeks and all content copyright © 2010-2014, Exelixis Media Ltd | Terms of Use | Privacy Policy
All trademarks and registered trademarks appearing on Java Code Geeks are the property of their respective owners.
Java is a trademark or registered trademark of Oracle Corporation in the United States and other countries.
Java Code Geeks is not connected to Oracle Corporation and is not sponsored by Oracle Corporation.

Sign up for our Newsletter

20,709 insiders are already enjoying weekly updates and complimentary whitepapers! Join them now to gain exclusive access to the latest news in the Java world, as well as insights about Android, Scala, Groovy and other related technologies.

As an extra bonus, by joining you will get our brand new e-books, published by Java Code Geeks and their JCG partners for your reading pleasure! Enter your info and stay on top of things,

  • Fresh trends
  • Cases and examples
  • Research and insights
  • Two complimentary e-books