Generic DAO for Hibernate

Do you have a project with many DAOs which are same except an attribute called “tableName”? If so, you may want to get rid of this and replace this pile of copied and pasted classes with a single one, right?

I created a generic DAO class for Hibernate, let me show you how to use it within a simple usage, for instance a user table. As I want to focus on the generic DAO’s behavior, I will pass over security.

First, we have a mapping file, user.hbm.xml :

<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
	"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
	"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping package="org.debril.lib.example">
  <class name="User" table="user">
        <id name="id" column="user_id">
            <generator class="native"/>
        </id>
        <property name="login" type="java.lang.String"/>
  		<property name="password" type="java.lang.String"/>
        <property name="firstName" type="java.lang.String"/>
        <property name="lastName" type="java.lang.String"/>
        <property name="email" type="java.lang.String"/>
  </class>
</hibernate-mapping>

Now let’s see the associated persistent class, User.java :

import java.io.Serializable;
public class User implements Serializable {
    private static final long serialVersionUID = 1L;
    private int id;
    private String login;
    private String password;
    private String firstName;
    private String lastName;
    private String email;

    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }
    public String getLogin() {
        return login;
    }
    public void setLogin(String login) {
        this.login = login;
    }
    public String getPassword() {
        return password;
    }
    public void setPassword(String password) {
        this.password = password;
    }
    public String getFirstName() {
        return firstName;
    }
    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }
    public String getLastName() {
        return lastName;
    }
    public void setLastName(String lastName) {
        this.lastName = lastName;
    }
    public String getEmail() {
        return email;
    }
    public void setEmail(String email) {
        this.email = email;
    }

}

then, let’s create a new user :

        User user = new User();
        user.setFirstName("Steve");
        user.setLastName("Jobs");
	user.setLogin("sjobs");

And now we want to save it using an accurate DatabaseAccessObject instance :

	//create a new DatabaseAccessObject adapted to the User class
	DatabaseAccessObject<User> dao = new DatabaseAccessObject<User>( User.class );

	//now save the new user
	dao.save( user );

You have probably noticed the User.class argument passed to the constructor. When Hibernate fetches records from database and casts it into persistent objects it needs to know which class to use. Back to to the example, we can see the above code does not compile : there is an unhandled SaveFailureException. As all exception thrown by Hibernate are wrapped within a HibenateException, it may be easier to deal with if the method that raised the exception could throw an explicit one.

        //create a new DatabaseAccessObject adapted to the User class
        DatabaseAccessObject<User> dao = new DatabaseAccessObject<User>( User.class );

        try {
            //now save the new user
            dao.save( user );
        } catch (SaveFailureException e) {
            //manage the exception... 
        }

Finally, we want to fetch one record from the database. The databaseAccessObject may throw a DataNotFoundException if you try to fetch a row that does not exist, which is cleaner than the null pointer Hibernate uses to return in that case :

        int id = 1;
        String login = "sjobs";
        try {
            //find the record using its unique id ( must an integer )...
            user = dao.find( id );
            //... or find the record using a field
            user = dao.find("login", login);
        } catch (DataNotFoundException e) {
            //manage the exception...
        }

If you are interested in using this library, you are welcome to download the files below :

jar file

javadoc

- source code

No comments yet

Leave a reply