Oct 17, 2008

Fast and easy Hibernate example-tutorial (Part 1)

This tutorial tries to provide fast and easy instructions on getting started with Hibernate. You can download Hibernate from http://www.hibernate.org.
I won't explain how to make Java project with eclipse or netbeans, it is beyond the scope of this text.

Hibernate is an open-source ORM(object relational mapping) library. It is one of the basic tools for fast and reliable java application development. Hibernate is published under LGPL license that allows you to use it in both open-source and commercial projects.

The fastest way to learn something new is with examples. So I'll write some basic example for its usage. For this exercise I'll use PostgreSQL as my database server. It doesn't matter so much, changing to another type is easy from the Hibernate configuration file.

Lets have database called 'example' with table 'books'. Books will have 3 columns - id, title and author.
Here is our persistent class - I'll call it Book


public class Book {
private Integer id;

private String title;

private String author;

public String getAuthor() {
return author;
}

public void setAuthor(String author) {
this.author = author;
}

public Integer getId() {
return id;
}

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

public String getTitle() {
return title;
}

public void setTitle(String title) {
this.title = title;
}
}



And this would be our mapping xml file Book.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>

<class name="Book" table="books">

<id name="id" column="id">

<generator class="native"/>

</id>

<property name="title" column="title" type="java.lang.String" />

<property name="author" column="author" type="java.lang.String" />

</class>

</hibernate-mapping>



This is the Hibernate configuration file :

<!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="hibernate.dialect">org.hibernate.dialect.PostgreSQLDialect</property>

<property name="hibernate.connection.driver_class">org.postgresql.Driver</property>

<property name="hibernate.connection.url">jdbc:postgresql://localhost/example</property>

<property name="hibernate.connection.username">username</property>

<property name="hibernate.connection.password">secret</property>

<property name="connection.pool_size">1</property>

<property name="show_sql">true</property>

<mapping resource="Book.hbm.xml" />

</session-factory>

</hibernate-configuration>




Now we are ready to test what we've done. Lets make simple text class BookExercise.

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;


public class BookExercise {
public static void main(String[] args) {
SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();
Session session = sessionFactory.openSession();

Book firstBook = new Book();
firstBook.setId(1);
firstBook.setTitle("Our first book title");
firstBook.setAuthor("Our Author");

Book secondBook = new Book();
secondBook.setId(2);
secondBook.setTitle("Second book title");
secondBook.setAuthor("Our Author");

Transaction tx = session.beginTransaction();

session.saveOrUpdate(firstBook);
session.saveOrUpdate(secondBook);

tx.commit();

session.close();
sessionFactory.close();
}
}


Now you must have two records in your books table. To view them you can try to change the exercise class this way:


import java.util.Iterator;
import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;


public class BookExercise {
public static void main(String[] args) {
SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();
Session session = sessionFactory.openSession();

Criteria criteria = session.createCriteria(Book.class);
List books = criteria.list();

Iterator it = books.iterator();
while(it.hasNext()) {
Book book = (Book) it.next();
System.out.println("Book: " + book.getTitle() + " with author: " + book.getAuthor());
}

session.close();
sessionFactory.close();
}
}

10 comments:

Krishna said...

nice article. hibernate

Anonymous said...

Dec 19, 2008 6:58:32 PM org.slf4j.impl.JCLLoggerAdapter error
SEVERE: ERROR: relation "hibernate_sequence" does not exist
Exception in thread "main" org.hibernate.exception.SQLGrammarException: could not get next sequence value

ihsan said...

Nice Articel..Help me so Much..

Anonymous said...

Thank you. Very helpfull stuff for begginers.

Anonymous said...

Thank you for giving an overview.

Andy R said...

I get:

Hibernate: update books set title=?, author=? where id=?
org.hibernate.StaleStateException: Batch update returned unexpected row count from update [0]; actual row count: 0; expected: 1

when I run this. Any thoughts?

Andy R said...

My problem went away when I deleted firstBook.setId(1); and firstBook.setId(2);

Hibernate creates the id values itself.

Anonymous said...

simply superb example for beginners

Anonymous said...

Nicely presented tutorial.

teJa said...

Realy a nice example,
Thank you

Popular Posts