In this blog we’ll be looking at how to use hibernate tools with just ant. This may be useful if you need to plug some hibernate tasks into your build system or have them scripted in any way. We will create a stand-alone ant build file with the minimum number of required libraries.
I’ve extracted hibernate tools jar from eclipse hibernate plugin. You can find it in your eclipse installation directory, under plugins: plugins/org.hibernate.eclipse_X.X.X.X/lib/tools. Take hibernate-tools.jar and freemarker.jar. From plugins/org.hibernate.eclipse_X.X.X.X/lib/hibernate grab more jars:
You will also need org.apache.commons.logging.jar and JDBC driver. I use MySQL, so I’ve added mysql-connector-java-5.1.13.jar as well. Put all the jars into “lib” directory. Create other directories: classes, src and generated. Or don’t bother – download the whole lot as I’ve set it up.
We will use two sample entity classes (POJOs) for that example: Password and Resource. A Resource can contain many Passwords.
Next, let’s create simple hibernate.cfg.xml…
…and mapping files for password and resource.
Ant build file
Finally we can build build.xml! We’ll first add paths to the required jars, then define new task: hibernatetool. We can then use our new task via <hibernatetool> tag – see the code below, it’s pretty self-explanatory.
We are running above hbm2ddl task to export database schema into ./generated/sql.ddl file. Other tasks you can use are:
hbm2java – generate POJOs
hbm2dao – generate DAOs
hbmtemplate – generate any custom code you want using templates (aka scaffolding)