Java persistence with Hibernate

In short, Java is a great language for programming large applications. But at some time, when you have manually reused or remade a database handler, e.g. for SQL queries, you might think that there should and must be a simpler way of persisting your application “objects”. In this article I will try to transfer my knowledge on how to use Hibernate for that cause. I have yet to see a better framework for persisting. This tutorial can be applied on any application, J2SE and J2EE.

You will need the following knowledge:

  • how to create java projects in eclipse or netbeans
  • how to access or create a database with create permissions (if not you will have to create the tables manually).
  • how to connect to a database through JDBC (understanding of connection urls and drivers).

Download Hibernate Core, Hibernate Annotations, Simple Logging For Java (SL4J), Logging 4 Java (log4j) and MySQL Java Connector (or other suiting driver). Once you have downloaded these releases, you should copy all the jars listed below to a new folder (I have no idea if all of them is actually needed… figure that out yourself… it worked for me). Note that the included slf4j-api-1.5.2.jar from hibernate should be replaced with SL4J’s updated slf4j-api-1.5.6.jar. If you do not include log4j-1.2.15.jar, things won’t work. So make sure you have all the jars listed below, with the same version numbers.

  • antlr-2.7.6.jar
  • commons-collections-3.1.jar
  • dom4j-1.6.1.jar
  • ejb3-persistence.jar
  • hibernate3.jar
  • hibernate-annotations.jar
  • hibernate-commons-annotations.jar
  • javassist-3.4.GA.jar
  • jta-1.1.jar
  • log4j-1.2.15.jar
  • mysql-connector-java-5.1.7-bin.jar
  • slf4j-api-1.5.6.jar
  • slf4j-log4j12-1.5.6.jar

Create a new java project. Add the above libraries to the project. Create a new empty file [ hibernate.cfg.xml ] in the root of the source folder of the project (the default package). Fill this new hibernate configuration file with the following content:

<!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
    "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
  <session-factory>
    <property name="dialect">org.hibernate.dialect.MySQLDialect</property>
    <property name="connection.driver_class">com.mysql.jdbc.Driver</property>

    <property name="connection.url">jdbc:mysql://localhost:3306/test</property>
    <property name="connection.username">user</property>
    <property name="connection.password">pass</property>
    <property name="connection.pool_size">1</property>

    <property name="current_session_context_class">thread</property>
    <property name="cache.provider_class">org.hibernate.cache.NoCacheProvider</property>
    <property name="show_sql">true</property>
    <property name="hbm2ddl.auto">create</property>

    <mapping class="Person"/>
  </session-factory>
</hibernate-configuration>

Configure the properties according to your own database. Note that you must download the correct jdbc driver if the database is not mysql. Create new class Person in default package. Copy and paste over the following content:

import java.io.Serializable;

import javax.persistence.Entity;
import javax.persistence.Id;

@Entity
public class Person implements Serializable {
    @Id
    private Long id;

    private String name;

    public String getName() {
            return name;
    }

    public void setName(String n) {
            name = n;
    }

    public Long getId() {
            return id;
    }

    public void setId(Long i) {
            id = i;
    }

}

Create new class called whatever you like, mine is Main. Copy and paste over the following content. Remember to change the class name if its something other than Main:

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.AnnotationConfiguration;

public class Main {

    public static void main(String[] args) {

             SessionFactory sessionFactory = new AnnotationConfiguration()
                      .configure().buildSessionFactory();
             Session session = sessionFactory.openSession();
             Person person = new Person();
             person.setId((long)1);
             person.setName("Test");
             session.persist(person);
             session.close();
             sessionFactory.close();
             System.out.println("Person was saved successfully in database!");
    }

}

Run the Main class and voila! Finished! You have now persisted your first java object, without any clue on what SQL is!

If you have followed this tutorial, everything should work. Note that if you are not used to making java projects, things can be difficult to comprehend. Please post a comment, and I’ll try to fix ur problems.

If something is wrong in this tutorial I would be happy to know!

Share and Enjoy:
  • Digg
  • Sphinn
  • del.icio.us
  • Facebook
  • Mixx
  • Google Bookmarks

0 Response to “Java persistence with Hibernate”


  • No Comments

Leave a Reply