Fast and easy Hibernate example-tutorial (Part 1)In the first part of this tutorial we met the basic functionality of Hibernate. We store and retrieve some simple objects to and from the database.
This time I’ll make the example a little harder. Now our table books will have author_id instead of author(simple string for the name) and we will have table authors with two columns: id, name.
Let’s assume that our book can have single author but our authors may have many books. It is rather dull example, far away from the real world where one book may be written by more than ten people but it would be easy for my example this way.
Also I'll make the id keys serial - I don't want to bother to set ids.
Here is the Author class:
public class Author {
private Integer id;
private String name;
public Integer getId() {
return id;
}
public String getName() {
return name;
}
public void setId(Integer id) {
this.id = id;
}
public void setName(String name) {
this.name = name;
}
}
And the Author.hbm.xml mapping:
<?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="Author" table="authors">
<id name="id" type="java.lang.Integer" column="id">
<generator class="sequence">
<param name="sequence">authors_id_seq</param>
</generator>
</id>
<property name="name" column="name" type="java.lang.String" />
</class>
</hibernate-mapping>
Book.java:
public class Book {
private Integer id;
private String title;
private Author author;
public Integer getId() {
return id;
}
public String getTitle() {
return title;
}
public Author getAuthor() {
return author;
}
public void setId(Integer id) {
this.id = id;
}
public void setTitle(String title) {
this.title = title;
}
public void setAuthor(Author author) {
this.author = author;
}
}
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" type="java.lang.Integer" column="id">
<generator class="sequence">
<param name="sequence">books_id_seq</param>
</generator>
</id>
<property name="title" column="title" type="java.lang.String" />
<many-to-one name="author" class="Author" lazy="false">
<column name="author_id"></column>
</many-to-one>
</class>
</hibernate-mapping>
And finally the hibernate.cfg.xml:
<!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="cache.provider_class">org.hibernate.cache.NoCacheProvider</property>
<property name="connection.pool_size">1</property>
<property name="show_sql">true</property>
<mapping resource="Author.hbm.xml" />
<mapping resource="Book.hbm.xml" />
</session-factory>
</hibernate-configuration>
We have our classes and now we are ready to test them. This is a simple test example for storing objects:
import java.util.Iterator;
import java.util.List;
import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
public class BookExample {
public static void main(String[] args) {
SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();
Session session = sessionFactory.openSession();
Author author = new Author();
author.setName("Crazy book author First");
Author author2 = new Author();
author2.setName("Writer");
Book book = new Book();
book.setTitle("Crazy book");
book.setAuthor(author);
Book book2 = new Book();
book2.setTitle("Crazy old book");
book2.setAuthor(author);
Book book3 = new Book();
book3.setTitle("Book Title");
book3.setAuthor(author2);
Transaction tx = session.beginTransaction();
session.save(author);
session.save(author2);
session.save(book);
session.save(book2);
session.save(book3);
tx.commit();
session.close();
sessionFactory.close();
}
}
The result must be something like this:
Hibernate: select nextval ('authors_id_seq')
Hibernate: select nextval ('authors_id_seq')
Hibernate: select nextval ('books_id_seq')
Hibernate: select nextval ('books_id_seq')
Hibernate: select nextval ('books_id_seq')
Hibernate: insert into authors (name, id) values (?, ?)
Hibernate: insert into authors (name, id) values (?, ?)
Hibernate: insert into books (title, author_id, id) values (?, ?, ?)
Hibernate: insert into books (title, author_id, id) values (?, ?, ?)
Hibernate: insert into books (title, author_id, id) values (?, ?, ?)
And now to retrieve the objects from the database:
import java.util.Iterator;
import java.util.List;
import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
public class BookExample2 {
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().getName());
}
session.close();
sessionFactory.close();
}
}
The result:
Hibernate: select this_.id as id1_0_, this_.title as title1_0_, this_.author_id as author3_1_0_ from books this_
Hibernate: select author0_.id as id0_0_, author0_.name as name0_0_ from authors author0_ where author0_.id=?
Hibernate: select author0_.id as id0_0_, author0_.name as name0_0_ from authors author0_ where author0_.id=?
Book: Crazy book with author: Crazy book author First
Book: Book Title with author: Writer
Book: Crazy old book with author: Crazy book author First
In this example I use few rather interesting options. The first is the generator child element of id with option sequence. It uses a sequence from our database (PostgreSQL, remember? ).
The second is many-to-one relation between the objects with lazy set to false. This option tells Hibernate to retrieve the author object together with our book object. However, most of the time you will use lazy set to true, this is also the default value.