0% found this document useful (0 votes)
18 views

Hibernate JAVA Spring

This document provides an overview of how to get started with Hibernate annotations. It discusses when to use annotations, common annotations used, project setup, database configuration, creating annotated model classes, creating the database, and writing a test program.

Uploaded by

Mamadou Guindo
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
18 views

Hibernate JAVA Spring

This document provides an overview of how to get started with Hibernate annotations. It discusses when to use annotations, common annotations used, project setup, database configuration, creating annotated model classes, creating the database, and writing a test program.

Uploaded by

Mamadou Guindo
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 10

Getting Started With Hibernate Annotations http://www.codejava.net/frameworks/hibernate/getting-started-with-hi...

Getting Started With Hibernate Annotations


Last Updated on 18 February 2016 | Print Email

[SALE NOW] Top Java Programming Courses (Coupon Code: APR15203)


Table of content:

1. What’s in this tutorial?


2. When to use annotations?
3. Quick reference on annotations used
4. Tools needed
5. Project Structure
6. Setup Database Configuration
7. Create annotated model classes
8. Create Database
9. Writing Test Program

1. What’s in this tutorial?


We’ll setup a sample Hibernate application here which demonstrates the usage of annotations.

Create a database connection configuration using XML


Create model classes Person and Address and establish a many-to-many relationship between them and map them
with database using annotations
Obtain connection using Configuration object and build a SessionFactory object
Obtain Session objects to perform a save operation using Hibernate APIs

2. When to use annotations?


Use annotations to provide metadata configuration along with the Java code. That way the code is easy to understand. Annotations
are less powerful than XML configuration. XML also gives you the ability to change the configuration without building the project. So
use annotations only for table and column mappings, not for frequently changing stuff like database connection and other
properties. Annotations are preconfigured with sensible default values, which reduce the amount of coding required, e.g. class
name defaults to table name and field names defaults to column names.

3. Quick reference on annotations used


Annotation Modifier Description
@Entity Marks a class as a Hibernate Entity (Mapped class)
@Table Name Maps this class with a database table specified by
name modifier. If name is not supplied it maps the class
with a table having same name as the class
@Id Marks this class field as a primary key column
@GeneratedValue Instructs database to generate a value for this field
automatically
@Column Name Maps this field with table column specified by name and
uses the field name if name modifier is absent
Cascade Marks this field as the owning side of the many-to-many
relationship and cascade modifier specifies which
@ManyToMany operations should cascade to the inverse side of
relationship
mappedBy This modifier holds the field which specifies the inverse
side of the relationship
Name For holding this many-to-many relationship, maps this
field with an intermediary database join table specified
by name modifier
joinColumns Identifies the owning side of columns which are
@JoinTable necessary to identify a unique owning object
inverseJoinColumns Identifies the inverse (target) side of columns which are
necessary to identify a unique target object

1 sur 10 24/04/2017 09:43


Getting Started With Hibernate Annotations http://www.codejava.net/frameworks/hibernate/getting-started-with-hi...
@JoinColumn Name Maps a join column specified by the name identifier to
the relationship table specified by @JoinTable

4. Tools needed
Download latest version of Eclipse: http://www.eclipse.org/downloads
Download latest JDK: http://www.oracle.com/technetwork/java/javase/downloads/index.html
Download latest MySQL: http://dev.mysql.com/downloads/mysql
Download latest Hibernate distribution zip: http://sourceforge.net/projects/hibernate/files/hibernate4 (Hibernate 4.1.9 as of
writing)
Let’s presume you’ve unzipped the Hibernate distribution zip to a directory called Hibernate. You would need all the jar
files under Hibernate\lib\required and Hibernate\lib\jpa directories
MySQL Java Connector Jar: http://dev.mysql.com/downloads/connector/j If you want to learn more about Hibernate, find
and read this book: Java Persistence with Hibernate

5. Project Structure

6. Setup Database Configuration


Create hibernate.cfg.xml file as shown in above figure and configure the database connection and mapping classes. Here is
the XML configuration:

2 sur 10 24/04/2017 09:43


Getting Started With Hibernate Annotations http://www.codejava.net/frameworks/hibernate/getting-started-with-hi...

Here we instructed Hibernate to connect to a MySQL database named hibernateTutorial. As you can see, we supplied
database URL, username and password for the connection. We also instructed Hibernate to use MySQLDialect i.e. Hibernate will
optimize the generated SQL statements for MySQL. We also added couple of entities called Person and Address which we’ll
configure later. This configuration will be used to create a Hibernate SessionFactory object.

7. Create annotated model classes


Create model classes Person.java and map it to the database using annotations as follows:

3 sur 10 24/04/2017 09:43


Getting Started With Hibernate Annotations http://www.codejava.net/frameworks/hibernate/getting-started-with-hi...

4 sur 10 24/04/2017 09:43


Getting Started With Hibernate Annotations http://www.codejava.net/frameworks/hibernate/getting-started-with-hi...

Create model classes Address.java and map it to the database using annotations as follows:

5 sur 10 24/04/2017 09:43


Getting Started With Hibernate Annotations http://www.codejava.net/frameworks/hibernate/getting-started-with-hi...

6 sur 10 24/04/2017 09:43


Getting Started With Hibernate Annotations http://www.codejava.net/frameworks/hibernate/getting-started-with-hi...

8. Create Database
Now go to any MySQL query tool (Preferably SQLYog)

Create a database called hibernatetutorial with utf8 encoding:

Create person, address and person_address tables as follows:

Here’s the table relationship diagram:

7 sur 10 24/04/2017 09:43


Getting Started With Hibernate Annotations http://www.codejava.net/frameworks/hibernate/getting-started-with-hi...

As you can see, there is a one-to-many relationship between person and person_address, one-to-many relationship between
address and person_address and as a result of that, many-to-many relationship between person and address tables.

If you are new to Hibernate and want to learn more, read this book: Hibernate Made Easy: Simplified Data Persistence with
Hibernate and JPA (Java Persistence API) Annotations

9. Writing Test Program


Create a HibernateUtil class to read XML database configuration we did earlier and create a Configuration object to
obtain a SessionFactory object. Please make sure that hibernate.cfg.xml file is on the classpath. Following is code of the
HibernateUtil.java class:

Ideally, it’s a good practice to create one SessionFactory object per data store at global application level scope. Hence here we
are creating just one static SessionFactory object when the class is first loaded and then we access the same via
getSessionFactory() static method. This is the safest implementation of a singleton object.

Now let’s create a PersonManager class which creates 2 person and 3 address objects and persists them to the database. Note
8 sur 10 24/04/2017 09:43
Getting Started With Hibernate Annotations http://www.codejava.net/frameworks/hibernate/getting-started-with-hi...
that all the addresses have been persisted using Hibernate cascade functionality. Here is code of the PersonManager.java
class:

Just right click in the editor window and run the project as Java application. You should see following output in the console…

Here’s the final database presentation you should see:

Person table

9 sur 10 24/04/2017 09:43


Getting Started With Hibernate Annotations http://www.codejava.net/frameworks/hibernate/getting-started-with-hi...

Address table

Person_Address table

Above you can see that in person table, persons Steve and Donald have been saved with auto generated ids 1 and 2
respectively. In address table, addresses San Francisco, Chicago and New York have been saved with auto generated ids 1, 2
and 3 respectively. Also in person_address table person_id 1 is associated with address_id 1 and person_id 2 is
associated with address_ids 2 and 3 respectively.

This tutorial shows how easily you can configure session factory connection details using XML and entities using annotation
configuration respectively in Hibernate and access the database. By using XML, database connection properties can be easily
changed without changing the Java source files which is an added advantage. By using annotations, Java entity classes are more
expressive and you don’t have to refer to another XML file for figuring out the Hibernate-Database mapping.

Above shown code snippets can be downloaded as a full Eclipse project along with the accompanying jar files from the attachment
section.

You may be also interested in:


Writing a basic Hibernate-based program with Eclipse
Building Hibernate SessionFactory from Service Registry
Hibernate Query Language (HQL) Example
Hibernate Basics - 3 ways to delete an en ty from the datastore

Share this article:

Attachments:
HibernateAnnotationTutorial.zip [ ] 6267 kB

Gestionnaire de tâches

10 sur 10 24/04/2017 09:43

You might also like