Hibernate, lesson 1 – first encounter

Hibernate is one of the most popular java technologies there is and it seems it is not going anywhere for at least 10 years.
If you are a java developer you can’t afford not to know it, at least on the surface.

This post is for those of you who never used hibernate, or used it and just want to start from scratch.
If hibernate seems like a tech-monster for you, you’ll come to the right place.
I’ll show you how to get hibernate to work in a very short time.

What do you need?

  1. DB connection
  2. Basic SQL knowledge
  3. Java knowledge + IDE

Step 1 – Download Hibernate

  • Download Hibernate Core¬† zip file form http://www.hibernate.org/6.html.
  • Unzip it.
  • The most impotent file is hibernate3.jar. Locate it under the root.
  • Other important jars can be found under the lib folder

Step 2 – Start a new java project with your IDE

  • Add the hibernate3.jar to the classpath.
  • Also add these jars: dom4j, log4j, slf4j-api,¬† slf4j-jcl, commons-logging, commons-collection, javassist, jta, antlr (most of them come with hibernate)
  • Add also the driver jar + license to the classpath.

Step 3 – Create a java bean

  • A bean is a java class with a default constructor, members, getters and setters.
  • For a start, use only primitive types and string for members.

example:

package com.avi;

public class Contact {
 private long id;
 private String firstName;
 private String lastName;
 private String email;

 public Contact() {

 }

 public long getId() {
 	return id;
 }

 public void setId(long id) {
 	this.id = id;
 }

  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;
 }

}

Step 4 – Add *.hbm.xml file

  • This is the mapping file. I maps between the bean and the DB.
  • It holds the field mapping.
  • It also holds queries.
  • It holds the id, which is the primary key of the DB. The id has a generator tag which determines how the id is generated.

example:

<?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>
  <class name="com.avi.Contact" table="CONTACT" lazy="true" >
	   <id name="id" type="long" column="ID"  >
	   <generator class="assigned"/>
	   <!--  generator class="increment"/>  -->
	  </id>

	  <property name="firstName" >
		 <column name="FIRSTNAME" />
	  </property>
	  <property name="lastName">
		<column name="LASTNAME"/>
	  </property>
	  <property name="email">
		<column name="EMAIL"/>
	  </property>
	  
   </class>
   
    <query name="getContactById" >from Contact where id=?</query>
</hibernate-mapping>

Step 5 – Add hibernate.cfg.xml

  • This is the most important configuration file for Hibernate.
  • It holds many many important properties:
    • DB connection properties.
    • DB Dialect – every DB type has it’s own dialect.
    • Reference to the hbm file you have added in step 4.
    • There are many more properties you can add, but for now we wont use them.

example:

<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">

<hibernate-configuration>
<session-factory>

<!-- DB connection properties -->
      <property name="hibernate.connection.driver_class">org.hsqldb.jdbcDriver</property>
      <property name="hibernate.connection.url">jdbc:hsqldb:mem:.</property>
      <property name="hibernate.connection.username">sa</property>
      <property name="hibernate.connection.password"></property>
      <property name="hibernate.connection.pool_size">10</property>
      
      
      <property name="show_sql">true</property>
      <property name="dialect">org.hibernate.dialect.HSQLDialect</property>
      
<!-- creates the DB -->      
      <property name="hibernate.hbm2ddl.auto">create</property>
      <!-- Mapping files -->
      <mapping resource="contact.hbm.xml"/>
</session-factory>
</hibernate-configuration>

Step 6 – Write a java code which triggers the whole thing

  • In this step you will write a short java code which will use hibernate.
  • Your code need to have these parts:
    • Create session factory
    • open session
    • make a query
    • session flush + close

example:

 private void insertContact(Contact contact){
   	 sessionFactory = 
            new Configuration().configure().buildSessionFactory();
            
       Session session = sessionFactory.openSession();
       Transaction transaction = session.beginTransaction();

        //making a query
       session.save(contact);

       transaction.commit();
       session.flush();
       session.close();
    }

When you will use this code for the first time, the DB table will be created automatically.

Believe it or not, this is it. you are now using hibernate.

But don’t stop here. Hibernate is a whole world. The options are endless.

downloaddownload source

Leave a Reply

Your email address will not be published.