Monday, June 20, 2011

DB Creation using maven hibernate

nice to have is a profile to create the database from the jpa annotations.

We can setup hibernate tools to do that for us in a separate profile.

IT IS IMPORTANT to run the hbm2ddl goal AFTER the compile phase since the information collected from the annotations in the compile are defining the schema in an application solely relying on annotations for config!

mvn -P createDb process-classes


<profile>
<id>createDb</id>
<!-- CREATE application DATABASE ******************************************************* -->
<build>
<plugins>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>sql-maven-plugin</artifactId>
<configuration>
<driver>${jdbc.driverClassName}</driver>
<!-- connect to root DB -->
<url>jdbc:mysql://localhost/root</url>
<!-- settingsKey is name for server setting in settings.xml used for authentication -->
<settingsKey>${tomcat.root.server}</settingsKey>
</configuration>
<executions>
<execution>
<id>drop-schemas</id>
<phase>validate</phase>
<goals>
<goal>execute</goal>
</goals>
<configuration>
<autocommit>true</autocommit>
<sqlCommand> DROP SCHEMA IF EXISTS ${jpa.persistenceUnit}; </sqlCommand>
<onError>continue</onError>
</configuration>
</execution>
<execution>
<id>create-schema</id>
<phase>validate</phase>
<goals>
<goal>execute</goal>
</goals>
<configuration>
<autocommit>true</autocommit>
<sqlCommand> CREATE SCHEMA IF NOT EXISTS ${jpa.persistenceUnit}; </sqlCommand>
<onError>continue</onError>
</configuration>
</execution>
<execution>
<id>grant-access</id>
<phase>validate</phase>
<goals>
<goal>execute</goal>
</goals>
<configuration>
<sqlCommand>grant ALL PRIVILEGES ON ${jpa.persistenceUnit}.* TO ${jdbc.username}@'%';</sqlCommand>
<onError>continue</onError>
</configuration>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>hibernate3-maven-plugin</artifactId>
<executions>
<execution>
<id>createTables</id>
<phase>process-classes</phase>
<goals>
<goal>hbm2ddl</goal>
</goals>
</execution>
</executions>
<configuration>
<components>
<component>
<name>hbm2ddl</name>
<implementation>jpaconfiguration</implementation>
<outputDirectory>target/hibernate3/sql</outputDirectory>
</component>
</components>
<componentProperties>
<drop>true</drop>
<create>true</create>
<update>true</update>
<export>true</export>
<scan-classes>true</scan-classes>
<persistenceunit>${jpa.persistenceUnit}</persistenceunit>
<outputfilename>${jpa.persistenceUnit}_schema.sql</outputfilename>
</componentProperties>
</configuration>
</plugin>
</plugins>
</build>
</profile>

No comments: