Because I am constantly busy working on something, I have never had time to actually put everything in words and pictures. But, since you got here, then you must have already seen some part of my work - and this is the way I’m talking. I'm 24, born in Romania, studied at UPG Romania in software development field. I started from 0, mostly with basic stuff, and I’m evolving every day to an expert. I'm focused on freelancing projects, from small websites, to really heavy stuff.

Wednesday, March 30, 2011

How to generate DAO classes for Hibernate with JDBC transaction factory

If you need to generate DAO classes (Home classes) for Hibernate based on JDBC transaction factory, then in a start folder you need:

• A folder named hbm2java_gen that contains all the POJOs classes.
• The below ant script (named hbm2daoJNDI_JDBCTransactionFactory.xml):

<project name="Hibernate Tools for Ant - hbm2daoJDBC" default="run">
<target name="clean">
<delete dir="JDBC_java/classes"/>
<delete dir="JDBC_java/jar"/>
<target name="compile" depends="clean">
<mkdir dir="JDBC_java/classes"/>
<javac srcdir="JDBC_java/src" destdir="JDBC_java/classes"/>
<target name="jar" depends="compile">
<mkdir dir="JDBC_java/jar"/>
<jar destfile="JDBC_java/jar/GenerateDAOForJDBC.jar"
<attribute name="Main-Class"
<target name="run" depends="jar">
<java jar="JDBC_java/jar/GenerateDAOForJDBC.jar" fork="true"/>

• The JDBC_java folder that can be downloaded from
• A folder named hbm2daojdbc_gen folder that will contain the generated DAOs.

Now, you can generate the DAOs, like this:

1. Edit /JDBC_java/src/ file, to specify your application package (by default, it is set to com.hibernate.demo).
2. Run the above Ant script with:

ant –f hbm2daoJNDI_JDBCTransactionFactory.xml

A generated transaction will be of form (supposing a User POJO class):

public void persist(Users transientInstance) {
log.debug("Persisting Users instance");
try {
log.debug("Persist successful");
} catch (RuntimeException re) {
log.error("Persist failed", re);
throw re;

For Tomcat users, in the JDBC_java/src/ you can find a simple example of web.xml and META-INF/context.xml for configuring datasource connection through JNDI.

A possible hibernate.cfg.xml for this case will look like below:
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
<property name="hibernate.connection.datasource">java:/comp/env/jdbc/usersdb
<property name="hibernate.current_session_context_class">thread</property>
<property name="hibernate.transaction.factory_class">
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<mapping resource="com/hibernate/demo/Users.hbm.xml" />

This post is just one of a set of Ant scripts that explores Hibernate Tools for Ant. The complete set can be downloaded from here ( ).

No comments: