DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports Events Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
Zones
Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Join us today at 1 PM EST: "3-Step Approach to Comprehensive Runtime Application Security"
Save your seat
  1. DZone
  2. Data Engineering
  3. Databases
  4. Hibernate 3 Annotations Tutorial

Hibernate 3 Annotations Tutorial

Loiane Groner user avatar by
Loiane Groner
·
Jun. 15, 10 · Tutorial
Like (0)
Save
Tweet
Share
123.84K Views

Join the DZone community and get the full member experience.

Join For Free

 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.xmlas 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 YorkRio de JaneiroTokyoLondonHibernate: 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 YorkRio de JaneiroParis

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

Hibernate Database Annotation

Opinions expressed by DZone contributors are their own.

Popular on DZone

  • Fraud Detection With Apache Kafka, KSQL, and Apache Flink
  • Using JSON Web Encryption (JWE)
  • Why Every Fintech Company Needs DevOps
  • Choosing the Best Cloud Provider for Hosting DevOps Tools

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 600 Park Offices Drive
  • Suite 300
  • Durham, NC 27709
  • support@dzone.com
  • +1 (919) 678-0300

Let's be friends: