SQL Zone is brought to you in partnership with:

Loiane Groner, Brazilian, works as a Java/ Sencha evangelist. She has 7+ years of experience in web development. She is the ESJUG (Espirito Santo Java Users Group) and CampinasJUG (Campinas Java Users Group) leader and coordinator. Loiane is passionate about technology and programming. Also author of ExtJS 4 First Look book. Loiane is a DZone MVB and is not an employee of DZone and has posted 42 posts at DZone. You can read more from them at their website. View Full User Profile

Hibernate 3 Annotations Tutorial

06.15.2010
| 99209 views |
  • submit to reddit

 This tutorial will walk through how to implement a hello world project using Hibernate Annotations and MySQL database.

Requirements

  • Download and unzip Hibernate Core distribution from the Hibernate website. Hibernate 3.5 and onward contains Hibernate Annotations.
  • Starting with version 3.5 (currently trunk), Annotations and EntityManager have been merged back into the Hibernate Core codebase as invidual modules.  We will also begin bundling Envers at the same time.  This will significantly help simplify compatibility guidelines.

  • Download SLF4 lib as well.
  • Download the database connector. In this example, I’m using MySQL database.

Configuration

First, set up your classpath:

  • Copy hibernate3.jar and the required 3rd party libraries available in lib/required.
  • Copy lib/jpa/hibernate-jpa-2.0-api-1.0.0.Final.jar to your classpath as well.
  • Also copy slf4j-simple-1.5.8.jar from SLF4 (I’ve got an exception without this lbi in my classpath)

The picture will all required libraries is given bellow:

Let’s start by creating our POJO (Plain Old Java Object) class that represents the table in the database.

This is the City table:

And here is the City class:


package com.loiane.com.model;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;

@Entity
@Table(name="CITY")
public class City {

private long id;

private String name;

public City(String name) {
super();
this.name = name;
}

public City() {}

@Id
@GeneratedValue
@Column(name="CITY_ID")
public long getId() {
return id;
}

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

@Column(name="CITY_NAME", nullable=false)
public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}
}
Here is a list of all annotations used and its meaning:
  • @Entity declares the class as an entity (i.e. a persistent POJO class)
  • @Table is set at the class level; it allows you to define the table, catalog, and schema names for your entity mapping. If no @Table is defined the default values are used: the unqualified class name of the entity.
  • @Id declares the identifier property of this entity.
  • @GeneratedValue annotation is used to specify the primary key generation strategy to use. If the strategy is not specified by default AUTO will be used.
  • @Column annotation is used to specify the details of the column to which a field or property will be mapped. If the @Column annotation is not specified by default the property name will be used as the column name.

You also need to create the HibernateUtil class. The HibernateUtil class helps in creating the SessionFactory from the Hibernate configuration file. Its implementation is shown below:

package com.loiane.util;

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

import com.loiane.com.model.City;

public class HibernateUtil {

private static final SessionFactory sessionFactory;

static {
try {
sessionFactory = new AnnotationConfiguration()
.configure()
.addPackage("com.loiane.model") //the fully qualified package name
.addAnnotatedClass(City.class)
.buildSessionFactory();

} catch (Throwable ex) {
System.err.println("Initial SessionFactory creation failed." + ex);
throw new ExceptionInInitializerError(ex);
}
}

public static SessionFactory getSessionFactory() {
return sessionFactory;
}
}
  

You need to create a hibernate.cfg.xml as well, with all the information needed to connect to the database, such as database url, user, password:

<?xml version="1.0" encoding="UTF-8"?>
<!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.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.password">root</property>
<property name="hibernate.connection.url">jdbc:mysql://localhost/blog</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="connection.pool_size">1</property>
<property name="show_sql">true</property>
<property name="hbm2ddl.auto">create</property>
</session-factory>
</hibernate-configuration>

Here is an example of how to select, update, insert and delete a City:


package com.loiane.dao;

import java.util.List;

import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.Transaction;

import com.loiane.com.model.City;
import com.loiane.util.HibernateUtil;

public class CityDAO {

public Long saveCity(String cityName)
{
Session session = HibernateUtil.getSessionFactory().openSession();
Transaction transaction = null;
Long cityId = null;
try {
transaction = session.beginTransaction();
City city = new City();
city.setName(cityName);
cityId = (Long) session.save(city);
transaction.commit();
} catch (HibernateException e) {
transaction.rollback();
e.printStackTrace();
} finally {
session.close();
}
return cityId;
}

@SuppressWarnings("unchecked")
public void listCities()
{
Session session = HibernateUtil.getSessionFactory().openSession();
Transaction transaction = null;
try {
transaction = session.beginTransaction();
List<City> cities = session.createQuery("from City").list();

for (City city : cities){
System.out.println(city.getName());
}

transaction.commit();
} catch (HibernateException e) {
transaction.rollback();
e.printStackTrace();
} finally {
session.close();
}
}

public void updateCity(Long cityId, String cityName)
{
Session session = HibernateUtil.getSessionFactory().openSession();
Transaction transaction = null;
try {
transaction = session.beginTransaction();
City city = (City) session.get(City.class, cityId);
city.setName(cityName);
transaction.commit();
} catch (HibernateException e) {
transaction.rollback();
e.printStackTrace();
} finally {
session.close();
}
}

public void deleteCity(Long cityId)
{
Session session = HibernateUtil.getSessionFactory().openSession();
Transaction transaction = null;
try {
transaction = session.beginTransaction();
City city = (City) session.get(City.class, cityId);
session.delete(city);
transaction.commit();
} catch (HibernateException e) {
transaction.rollback();
e.printStackTrace();
} finally {
session.close();
}
}
}

and the Main class (you can try to run this class):

package com.loiane.main;

import com.loiane.dao.CityDAO;

public class Main {

public static void main(String[] args) {

CityDAO cityDAO = new CityDAO();

long cityId1 = cityDAO.saveCity("New York");
long cityId2 = cityDAO.saveCity("Rio de Janeiro");
long cityId3 = cityDAO.saveCity("Tokyo");
long cityId4 = cityDAO.saveCity("London");

cityDAO.listCities();

cityDAO.updateCity(cityId4, "Paris");

cityDAO.deleteCity(cityId3);

cityDAO.listCities();
}
}

If your setup is OK, this is the output:

Hibernate: insert into CITY (CITY_NAME) values (?)
Hibernate: insert into CITY (CITY_NAME) values (?)
Hibernate: insert into CITY (CITY_NAME) values (?)
Hibernate: insert into CITY (CITY_NAME) values (?)
Hibernate: select city0_.CITY_ID as CITY1_0_, city0_.CITY_NAME as CITY2_0_ from CITY city0_
New York
Rio de Janeiro
Tokyo
London
Hibernate: select city0_.CITY_ID as CITY1_0_0_, city0_.CITY_NAME as CITY2_0_0_ from CITY city0_ where city0_.CITY_ID=?
Hibernate: update CITY set CITY_NAME=? where CITY_ID=?
Hibernate: select city0_.CITY_ID as CITY1_0_0_, city0_.CITY_NAME as CITY2_0_0_ from CITY city0_ where city0_.CITY_ID=?
Hibernate: delete from CITY where CITY_ID=?
Hibernate: select city0_.CITY_ID as CITY1_0_, city0_.CITY_NAME as CITY2_0_ from CITY city0_
New York
Rio de Janeiro
Paris
  

You do not need to worry about creating the table in the database.The bellow configuration does it for you!

<property name="hbm2ddl.auto">create</property>

For more information about Hibernate Annotations, please read the Hibernate Documentation.

You can download the complete source code (including all the libraries) from my GitHub repository: http://github.com/loiane/hibernate-annotations

I developed this sample project using Eclipse IDE.

From http://loianegroner.com/2010/06/hibernate-3-annotations-tutorial

Published at DZone with permission of Loiane Groner, author and DZone MVB.

(Note: Opinions expressed in this article and its replies are the opinions of their respective authors and not those of DZone, Inc.)

Tags:

Comments

Adedayo Ominiyi replied on Tue, 2010/06/15 - 6:19am

Hi, nice tutorial. Wondering why u didn't use the standard EntityManager since u r using JPA annotations

Xavier Dury replied on Tue, 2010/06/15 - 6:48am

It's really nice to put up something like that... but please provide some correct examples:

  • why would you do a GET by id to perform a DELETE immediately after? why not doing a LOAD instead to save one db round-trip?
  • when configuring the sessionFactory, why add package AND class?
  • why do you open a new session/transaction in each DAO method? many people have argued how bad it is.

I know the purpose of this article is to bootstrap somebody who doesn't know how to use JPA annotations with hibernate but I don't think a beginner should be pointed at examples that will give him/her bad habits (and I've seen my share of programmers using hibernate very badly and then blaming it for bad performances).

Eduard Korenschi replied on Tue, 2010/06/15 - 1:04pm

OK, so the endeavor is nice, the effort is admirable, but:

Why not complete it with some info on spring? You would have to put just very few lines in an xml (basically just to configure your dataSource, entityManagerFactory / sessionFactory and transactionManager, which takes not more than 20 lines of xml. But then for all your daos/services it would only take an @Transactional annotation at class or method level to replace all your

Session session = HibernateUtil.getSessionFactory().openSession();

Transaction transaction = null;

     try {           transaction = session.beginTransaction();xxxxxxxxxxxxxx

transaction.commit();

       } catch (HibernateException e) {            transaction.rollback();         e.printStackTrace();        } finally {         session.close();        }   }}code. In your examples, you have so many lines of code when only xxxxxx (that is one, at most two lines of code) is important. Cheers, Eduard Korenschi

Walter Bogaardt replied on Wed, 2010/06/16 - 12:50am

Now go for @Embedded, and how that works. ;)

 

 

Slava Lo replied on Fri, 2010/06/25 - 7:48am

In support to teach good habbits, since you have slf4j in your classpath why not to use logger for output.

Never use System.out.println in your code, who knows if somebody is going to copy-paste this code and use it in production, and than app server system out log file will be spammed with those print-outs and annoy middleware support guys.

Michael Eric replied on Wed, 2012/09/26 - 3:41pm

Hi,
It’s nice but can anyone tell how to deal with 0ne-to-one , one-to-many, many-to-one mapping in hibernate using annotations

linux archive 

Comment viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.