Generate DDL with Hibernate Tools, JPA and Maven

It is very convenient to get the SQL you need to setup your database generated by you. The information is all there in your JPA annotated classes.

Hibernate Tools

Hibernate provides for that purpose the really great Hibernate Tools. But these tools are eclipse or ANT based. No official Maven support.

hibernate3-maven-plugin

Indeed there exists a Maven plugin at Codehaus, the hibernate3-maven-plugin. But this is (as the name states) only for hibernate 3.x and does not support hibernate 4.
Searching in the net revealed, that it could take a while until the new hibernate version would be supported (e.g. https://community.jboss.org/thread/203735).

Solution: ant-run Plugin

Luckily Maven has the possibility to execute ANT tasks. So the obvious solution is to just use the ant-run plugin and execute the hibernate-tools ANT target. Well, would be if you are an expert in Maven AND ANT classpaths :-). For me it took several hours to find the following solution:


  maven-antrun-plugin
  1.2
  
	  
		  install
		  
			  run
		  
	  
  
  
	  
		  
		  
			  
		  
		  
		  
		  
		  
		  
			  
			  
			  
		  
	  
	  true
  
  
	  
		  org.hibernate
		  hibernate-tools
		  4.0.0-CR1
		  
			  
				  hibernate-commons-annotations
				  org.hibernate
			  
		  
	  
	  
		  org.slf4j
		  slf4j-simple
		  ${slf4j.version}
	  
	  
		  org.slf4j
		  slf4j-api
		  ${slf4j.version}
	  
	  
		  mysql
		  mysql-connector-java
		  5.1.6
	  
  

I use the test classpath because I already create (with the help of the jpa-maven-plugin) a persistence.xml with all classes included for testing purposes. Just added a more production like unit to be used:

    
        org.hibernate.ejb.HibernatePersistence
        ${entityClassnames}
        
            
            
            
        
    

and the pom plugin entries for generating the entity class list, inserting it into the template persitence.xml and adding this directory to the test classpath:


	com.edugility
	jpa-maven-plugin
	1.0
	
		
			Generate entityClassnames.properties
			generate-resources
			
				list-entity-classnames
			
		
	


	maven-resources-plugin
	2.5
	
		
			Copy persistence.xml filtered with generated entityClassnames.properties file
			generate-resources
			
				copy-resources
			
			
				
					${project.build.directory}/generated-test-sources/jpa-maven-plugin/entityClassnames.properties
				
				${project.build.directory}/generated-test-sources/persistence/META-INF
				
					
						true
						src/process/test/resources
						
							persistence.xml
						
					
				
			
		
	


	org.codehaus.mojo
	build-helper-maven-plugin
	1.7
	
		
			add-test-resources
			generate-test-resources
			
				add-test-resource
			
			
				
					
						target/generated-test-sources/persistence