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

We have talent and the entire world is going to know it!

As some of you may know, Vivendi Games Mobile has just ceased its activity, despite our latest success with Crash Nitro Kart on iPhone. And as it gave us some hours to waste during the closing process, we decided to find a smart and useful way to fill in time. We finally developed http://talented-people.org and offered there the possibility to publish their résumé to all former Vivendi Games Europe employees.

Approximately 100 profiles are published by now, so if are interested in hiring some qualified video games professionals, you might find there the candidate who will match your needs. And if you are looking for a lead web programmer or a senior web programmer or a web architect, you can check my profile there, I am open to opportunities all around the world.

XP-Dev and free Subversion book

If you are looking for a good Subversion hosting with no charge, then check http://xp-dev.com . This site provides a free 1.5Go space where you create as many SVN repositories as you wish ( !!! ). Every wise man may ask “why is it free without any ads?”, well the author gives a proper explanation on his blog : http://roopindersingh.com/2008/11/01/free-subversion-hosting/

So if you are looking for a really good  subversion hosting with high availability and high performances, then just sign up on http://xp-dev.com . Moreover, it is the easiest way for you to thank Roopinder Singh for that great initiative.

Free again : “Version Control wih Subversion” published by O’Reilly Media at this location : http://svnbook.red-bean.com/ . Even thought this book is freely published on the internet, you can buy a copy on amazon.

I am still alive

I didn’t added any new post to this blog since a while ago, mainly because I had nothing to say. Moreover, I spent a countless amount of time during the last year designing and coding a management project within Vivendi Games Mobile, which brought me more skills than I would expect from it.
As you can see, I haven’t made any modification on phpWife, and its design is now completely out of my mind. This project is dead, for several reasons :

- I do not want to focus on PHP anymore, I want to develop skills related to many languages, such as Java or Ruby.

- Many PHP frameworks are doing well if you use them wisely

- I just don’t have the time. As a father of two young kids I must now put a lot of myself in my family (and I am strongly willing to ) .
With a little luck, I will become more active during the coming months.

xDebug & apd for Xampp linux 1.6.3 …

Oh my God, Things are going so fast …

xdebug_and_apd_for_xampp-1.6.3.tar.gz (hosted @ box.net)

And  now, I can go on holidays!

Have a nice profiling :)

xDebug & apd for Xampp linux 1.6.2

For all web developers willing to profile their scripts, you will find below an archive containing xDebug and apd compiled for Xampp 1.6.2 under linux.

xdebug_and_apd_for_xampp-1.6.2.tar.gz (hosted @ box.net)

Copy your archive in the /opt folder, then uncompress it and restart your xampp server :

cp xdebug_and_apd_for_xampp-1.6.2.tar.gz /opt
tar -xvzf xdebug_and_apd_for_xampp-1.6.2.tar.gz
lampp/lampp restart

This archive features xdebug.so, apd.so and php.ini configured so you will just need to restart your web server after uncompressing it.

Then, each time a PHP script is executed, a cachegrind.out file will be created in /tmp . This file is a trace of the whole script’s execution and brings a clear look on what is going on while the script is running. I suggest opening this file with kCachcgrind :

kcachegrind-1.png

kcachegrind-2.png

You can also use the xdebug functions inside your code (at the end of the main script):

if (extension_loaded('xdebug') ) {

    echo "<p>Memory Usage : "  . xdebug_memory_usage(). "</p>";

    echo "<p>duration : "  . xdebug_time_index(). "</p>";

}

that will print :

Memory Usage : 251992

duration : 0.00704598426819

Enjoy, and have a nice profiling :)

Smells to refactoring

Although “smells to Refactoring” is hosted on java.net, the suggested practices within this document are to be applied with any Object Oriented Programming (PHP, Java, Ruby, .Net, …). Every programmer must read it.

Long method is probably one of the most common code smell. Below a list of the troubles a 200 lines method can create :

  • it is hard to understand and hard to maintain. Mostly when the only comment can be found at the 130th line and looks like : “POST section”. Thank you very much.
  • it is so specific, it is totally impossible to use it in another context. Furthermore, it quickly becomes a copy/paste repository as some code blocks are closed to be generic snippets.
  • It is probably doing too much things. This statement becomes obvious as soon as you need to modify some behavior.
  • it is an open door to security issues. For two reasons: first, a large piece of code often comes with a high complexity, which is suitable for hard to find vulnerabilities. Then, it is easy to write a clean and secured method with only 15-20 lines, although the same care cannot be applied to a 200 lines method.

This kind of mistake can be easily avoided with a good conception prior to the coding process. Read the entire document, and you will probably conclude by yourself that most of the listed code smells are the aftermaths of a poor design.

Pear::DB is dead. Long live PDO!

Pear::DB is deprecated in favor of Pear::MDB2. I guess this is a good thing because MDB2 is faster, smaller and provides more features. I only guess because I am not a pear user,I do not like Pear as its installation is really weird and the documentation is sometimes insufficient.

By now, two database abstractions are still active in the PHP community : PDO & Pear::MDB2. I recommend PDO If you are writing your application using PHP5 and/or you want your application to be really fast (PDO is a PHP inner class). Pear::MDB2 can be a good thing for PHP4 applications or if you need a high-level of database abstraction in your application.

the Pear::MDB2 package : http://pear.php.net/package/MDB2/redirected

the PDO Class : http://php.net/manual/en/ref.pdo.php