0% found this document useful (0 votes)
278 views214 pages

Hibernate Tutorial

This document provides an overview and tutorial on Hibernate, an open source object-relational mapping tool for Java. It discusses what Hibernate is, its advantages like database independence and automatic table creation, its core architecture including sessions and transactions, and provides a basic example of creating a simple Hibernate application to store an object in a database without using an integrated development environment.

Uploaded by

sushain koul
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
278 views214 pages

Hibernate Tutorial

This document provides an overview and tutorial on Hibernate, an open source object-relational mapping tool for Java. It discusses what Hibernate is, its advantages like database independence and automatic table creation, its core architecture including sessions and transactions, and provides a basic example of creating a simple Hibernate application to store an object in a database without using an integrated development environment.

Uploaded by

sushain koul
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 214

Hibernate Tutorial

This hibernate tutorial provides in-depth concepts of Hibernate


Framework with simplified examples. It was started in 2001 by
Gavin King as an alternative to EJB2 style entity bean.

Hibernate Framework

Hibernate is a Java framework that simplifies the development of


Java application to interact with the database. It is an open
source, lightweight, ORM (Object Relational Mapping) tool.
Hibernate implements the specifications of JPA (Java Persistence
API) for data persistence.

ORM Tool

An ORM tool simplifies the data creation, data manipulation and


data access. It is a programming technique that maps the object
to the data stored in the database.

The ORM tool internally uses the JDBC API to interact with the
database.

What is JPA?
Java Persistence API (JPA) is a Java specification that provides
certain functionality and standard to ORM tools.
The javax.persistence package contains the JPA classes and
interfaces.

Advantages of Hibernate Framework

Following are the advantages of hibernate framework:

1) Open Source and Lightweight

Hibernate framework is open source under the LGPL license and


lightweight.

2) Fast Performance

The performance of hibernate framework is fast because cache is


internally used in hibernate framework. There are two types of
cache in hibernate framework first level cache and second level
cache. First level cache is enabled by default.

3) Database Independent Query

HQL (Hibernate Query Language) is the object-oriented version of


SQL. It generates the database independent queries. So you
don't need to write database specific queries. Before Hibernate, if
database is changed for the project, we need to change the SQL
query as well that leads to the maintenance problem.

4) Automatic Table Creation

Hibernate framework provides the facility to create the tables of


the database automatically. So there is no need to create tables
in the database manually.

5) Simplifies Complex Join

Fetching data from multiple tables is easy in hibernate


framework.
6) Provides Query Statistics and Database Status

Hibernate supports Query cache and provide statistics about


query and database status.

Hibernate Architecture

1. Hibernate Architecture
2. Elements of Hibernate Architecture
1. SessionFactory
2. Session
3. Transaction
4. ConnectionProvider
5. TransactionFactory

The Hibernate architecture includes many objects such as


persistent object, session factory, transaction factory, connection
factory, session, transaction etc.

The Hibernate architecture is categorized in four layers.

o Java application layer


o Hibernate framework layer
o Backhand api layer
o Database layer

Let's see the diagram of hibernate architecture:


This is the high level architecture of Hibernate with mapping file
and configuration file.
Hibernate framework uses many objects such as session factory,
session, transaction etc. alongwith existing Java API such as
JDBC (Java Database Connectivity), JTA (Java Transaction API)
and JNDI (Java Naming Directory Interface).

Elements of Hibernate Architecture

For creating the first hibernate application, we must know the


elements of Hibernate architecture. They are as follows:

SessionFactory

The SessionFactory is a factory of session and client of


ConnectionProvider. It holds second level cache (optional) of
data. The org.hibernate.SessionFactory interface provides factory
method to get the object of Session.

Session

The session object provides an interface between the application


and data stored in the database. It is a short-lived object and
wraps the JDBC connection. It is factory of Transaction, Query
and Criteria. It holds a first-level cache (mandatory) of data. The
org.hibernate.Session interface provides methods to insert,
update and delete the object. It also provides factory methods for
Transaction, Query and Criteria.

Transaction

The transaction object specifies the atomic unit of work. It is


optional. The org.hibernate.Transaction interface provides
methods for transaction management.

ConnectionProvider

It is a factory of JDBC connections. It abstracts the application


from DriverManager or DataSource. It is optional.

TransactionFactory

It is a factory of Transaction. It is optional.

First Hibernate Example without IDE

1. Steps to create first Hibernate Application


1. Create the Persistent class
2. Create the mapping file for Persistent class
3. Create the Configuration file
4. Create the class that retrieves or stores the persistent object
5. Load the jar file
6. Run the first hibernate application without IDE

Here, we are going to create the first hibernate application


without IDE. For creating the first hibernate application, we need
to follow the following steps:

1. Create the Persistent class


2. Create the mapping file for Persistent class
3. Create the Configuration file
4. Create the class that retrieves or stores the persistent object
5. Load the jar file
6. Run the first hibernate application by using command
prompt

1) Create the Persistent class

A simple Persistent class should follow some rules:

o A no-arg constructor: It is recommended that you have a


default constructor at least package visibility so that
hibernate can create the instance of the Persistent class by
newInstance() method.
o Provide an identifier property: It is better to assign an
attribute as id. This attribute behaves as a primary key in
database.
o Declare getter and setter methods: The Hibernate
recognizes the method by getter and setter method names
by default.
o Prefer non-final class: Hibernate uses the concept of
proxies, that depends on the persistent class. The
application programmer will not be able to use proxies for
lazy association fetching.

Let's create the simple Persistent class:


Employee.java
package com.javatpoint.mypackage;  
  
public class Employee {  
private int id;  
private String firstName,lastName;  
  
public int getId() {  
    return id;  
}  
public void setId(int id) {  
    this.id = id;  
}  
public String getFirstName() {  
    return firstName;  
}  
public void setFirstName(String firstName) {  
    this.firstName = firstName;  
}  
public String getLastName() {  
    return lastName;  
}  
public void setLastName(String lastName) {  
    this.lastName = lastName;  
}  
  
  
}  

2) Create the mapping file for Persistent class

The mapping file name conventionally, should be


class_name.hbm.xml. There are many elements of the mapping
file.

o hibernate-mapping : It is the root element in the mapping


file that contains all the mapping elements.
o class : It is the sub-element of the hibernate-mapping
element. It specifies the Persistent class.
o id : It is the subelement of class. It specifies the primary
key attribute in the class.
o generator : It is the sub-element of id. It is used to
generate the primary key. There are many generator classes
such as assigned, increment, hilo, sequence, native etc. We
will learn all the generator classes later.
o property : It is the sub-element of class that specifies the
property name of the Persistent class.

Let's see the mapping file for the Employee class:

employee.hbm.xml
<?xml version='1.0' encoding='UTF-8'?>  
<!DOCTYPE hibernate-mapping PUBLIC  
 "-//Hibernate/Hibernate Mapping DTD 5.3//EN"  
 "http://hibernate.sourceforge.net/hibernate-mapping-5.3.dtd">  
  
 <hibernate-mapping>  
  <class name="com.javatpoint.mypackage.Employee" table="emp
1000">  
    <id name="id">  
     <generator class="assigned"></generator>  
    </id>  
            
    <property name="firstName"></property>  
    <property name="lastName"></property>  
            
  </class>  
            
 </hibernate-mapping>  

3) Create the Configuration file


The configuration file contains information about the database
and mapping file. Conventionally, its name should be
hibernate.cfg.xml .

hibernate.cfg.xml
<?xml version='1.0' encoding='UTF-8'?>  
<!DOCTYPE hibernate-configuration PUBLIC  
          "-//Hibernate/Hibernate Configuration DTD 5.3//EN"  
          "http://hibernate.sourceforge.net/hibernate-configuration-
5.3.dtd">  
  
<hibernate-configuration>  
  
    <session-factory>  
        <property name="hbm2ddl.auto">update</property>  
        <property name="dialect">org.hibernate.dialect.Oracle9Dialec
t</property>  
        <property name="connection.url">jdbc:oracle:thin:@localhost
:1521:xe</property>  
        <property name="connection.username">system</property> 
 
        <property name="connection.password">jtp</property>  
        <property name="connection.driver_class">oracle.jdbc.driver.
OracleDriver</property>  
    <mapping resource="employee.hbm.xml"/>  
    </session-factory>  
  
</hibernate-configuration>  

4) Create the class that retrieves or stores the object

In this class, we are simply storing the employee object to the


database.

1. package com.javatpoint.mypackage;    
2.     
3. import org.hibernate.Session;    
4. import org.hibernate.SessionFactory;    
5. import org.hibernate.Transaction;  
6. import org.hibernate.boot.Metadata;  
7. import org.hibernate.boot.MetadataSources;  
8. import org.hibernate.boot.registry.StandardServiceRegistry
;  
9. import org.hibernate.boot.registry.StandardServiceRegistry
Builder;  
10.   
11.     
public class StoreData {    
public static void main(String[] args) {    
        
    //Create typesafe ServiceRegistry object    
    StandardServiceRegistry ssr = new StandardServiceRegistryBuil
der().configure("hibernate.cfg.xml").build();  
          
   Metadata meta = new MetadataSources(ssr).getMetadataBuilder(
).build();  
  
SessionFactory factory = meta.getSessionFactoryBuilder().build();  
Session session = factory.openSession();  
Transaction t = session.beginTransaction();   
            
    Employee e1=new Employee();    
    e1.setId(101);    
    e1.setFirstName("Gaurav");    
    e1.setLastName("Chawla");    
        
    session.save(e1);  
    t.commit();  
    System.out.println("successfully saved");    
    factory.close();  
    session.close();    
        
}    
}   
5) Load the jar file

For successfully running the hibernate application, you should


have the hibernate5.jar file.

Download the required jar files for hibernate

6) How to run the first hibernate application without IDE

We may run this hibernate application by IDE (e.g. Eclipse,


Myeclipse, Netbeans etc.) or without IDE. We will learn about
creating hibernate application in Eclipse IDE in next chapter.

To run the hibernate application without IDE:

o Install the oracle10g for this example.


o Load the jar files for hibernate. (One of the way to load the
jar file is copy all the jar files under the JRE/lib/ext folder).
It is better to put these jar files inside the public and private
JRE both.
o Now, run the StoreData class by java
com.javatpoint.mypackage.StoreData
Hibernate Example using XML in Eclipse

1. Example to create the Hibernate Application in Eclipse IDE


1. Create the java project
2. Add jar files for hibernate
3. Create the Persistent class
4. Create the mapping file for Persistent class
5. Create the Configuration file
6. Create the class that retrieves or stores the persistent object
7. Run the application

Here, we are going to create a simple example of hibernate


application using eclipse IDE. For creating the first hibernate
application in Eclipse IDE, we need to follow the following steps:
1. Create the java project
2. Add jar files for hibernate
3. Create the Persistent class
4. Create the mapping file for Persistent class
5. Create the Configuration file
6. Create the class that retrieves or stores the persistent object
7. Run the application

1) Create the java project

Create the java project by File Menu - New - project - java


project . Now specify the project name e.g. firsthb
then next - finish .

2) Add jar files for hibernate

To add the jar files Right click on your project - Build


path - Add external archives. Now select all the jar files as
shown in the image given below then click open.

Download the required jar file


In this example, we are connecting the application with oracle
database. So you must add the ojdbc14.jar file.

download the ojdbc14.jar file

3) Create the Persistent class

Here, we are creating the same persistent class which we have


created in the previous topic. To create the persistent class, Right
click on src - New - Class - specify the class with package name
(e.g. com.javatpoint.mypackage) - finish .

Employee.java
1. package com.javatpoint.mypackage;  
2.   
3. public class Employee {  
4. private int id;  
5. private String firstName,lastName;  
6.   
7. public int getId() {  
8.     return id;  
9. }  
10. public void setId(int id) {  
11.     this.id = id;  
12. }  
13. public String getFirstName() {  
14.     return firstName;  
15. }  
16. public void setFirstName(String firstName) {  
17.     this.firstName = firstName;  
18. }  
19. public String getLastName() {  
20.     return lastName;  
21. }  
22. public void setLastName(String lastName) {  
23.     this.lastName = lastName;  
24. }  
25. }  

4) Create the mapping file for Persistent class

Here, we are creating the same mapping file as created in the


previous topic. To create the mapping file, Right click
on src - new - file - specify the file name (e.g.
employee.hbm.xml) - ok. It must be outside the package.

employee.hbm.xml
1. <?xml version='1.0' encoding='UTF-8'?>  
2. <!DOCTYPE hibernate-mapping PUBLIC  
3.  "-//Hibernate/Hibernate Mapping DTD 5.3//EN"  
4.  "http://hibernate.sourceforge.net/hibernate-mapping-
5.3.dtd">  
5.   
6.  <hibernate-mapping>  
7.   <class name="com.javatpoint.mypackage.Employee" tabl
e="emp1000">  
8.     <id name="id">  
9.      <generator class="assigned"></generator>  
10.     </id>  
11.             
12.     <property name="firstName"></property>  
13.     <property name="lastName"></property>  
14.             
15.   </class>  
16.             
17.  </hibernate-mapping>  

5) Create the Configuration file

The configuration file contains all the informations for the


database such as connection_url, driver_class, username,
password etc. The hbm2ddl.auto property is used to create the
table in the database automatically. We will have in-depth
learning about Dialect class in next topics. To create the
configuration file, right click on src - new - file. Now specify the
configuration file name e.g. hibernate.cfg.xml.

hibernate.cfg.xml
1. <?xml version='1.0' encoding='UTF-8'?>  
2. <!DOCTYPE hibernate-configuration PUBLIC  
3.           "-//Hibernate/Hibernate Configuration DTD 5.3//EN"  
4.           "http://hibernate.sourceforge.net/hibernate-
configuration-5.3.dtd">  
5.   
6. <hibernate-configuration>  
7.   
8.     <session-factory>  
9.         <property name="hbm2ddl.auto">update</property>  
10.         <property name="dialect">org.hibernate.dialect.Oracl
e9Dialect</property>  
11.         <property name="connection.url">jdbc:oracle:thin:@l
ocalhost:1521:xe</property>  
12.         <property name="connection.username">system</pr
operty>  
13.         <property name="connection.password">oracle</prop
erty>  
14.         <property name="connection.driver_class">oracle.jdb
c.driver.OracleDriver</property>  
15.     <mapping resource="employee.hbm.xml"/>  
16.     </session-factory>  
17.   
18. </hibernate-configuration>  

6) Create the class that retrieves or stores the persistent object

In this class, we are simply storing the employee object to the


database.

1. package com.javatpoint.mypackage;  
2.   
3. import org.hibernate.Session;  
4. import org.hibernate.SessionFactory;  
5. import org.hibernate.Transaction;  
6. import org.hibernate.boot.Metadata;  
7. import org.hibernate.boot.MetadataSources;  
8. import org.hibernate.boot.registry.StandardServiceRegistry
;  
9. import org.hibernate.boot.registry.StandardServiceRegistry
Builder;  
10.   
11. public class StoreData {  
12.   
13.     public static void main( String[] args )  
14.     {  
15.          StandardServiceRegistry ssr = new StandardServiceR
egistryBuilder().configure("hibernate.cfg.xml").build();  
16.             Metadata meta = new MetadataSources(ssr).getMe
tadataBuilder().build();  
17.           
18.         SessionFactory factory = meta.getSessionFactoryBuild
er().build();  
19.         Session session = factory.openSession();  
20.         Transaction t = session.beginTransaction();  
21.           
22.          Employee e1=new Employee();    
23.             e1.setId(1);    
24.             e1.setFirstName("Gaurav");    
25.             e1.setLastName("Chawla");    
26.          
27.        session.save(e1);  
28.        t.commit();  
29.        System.out.println("successfully saved");    
30.         factory.close();  
31.         session.close();     
32.     }  
33. }  

7) Run the application

Before running the application, determine that directory


structure is like this.
To run the hibernate application, right click on the StoreData
class - Run As - Java Application.

Example to create the Hibernate Application in MyEclipse

1. Example to create the Hibernate Application in MyEclipse


2. Create the java project
3. Add hibernate capabilities
4. Create the Persistent class
5. Create the mapping file for Persistent class
6. Add mapping of hbm file in configuration file
7. Create the class that retrieves or stores the persistent object
8. Add jar file for oracle
9. Run the application

Here, we are going to create a simple example of hibernate


application using myeclipse IDE. For creating the first hibernate
application in MyEclipse IDE, we need to follow following steps:

1. Create the java project


2. Add hibernate capabilities
3. Create the Persistent class
4. Create the mapping file for Persistent class
5. Add mapping of hbm file in configuration file
6. Create the class that retrieves or stores the persistent object
7. Add jar file for oracle
8. Run the application

1) Create the java project

Create the java project by File Menu - New - project - java


project . Now specify the project name e.g. firsthb
then next - finish .

2) Add hibernate capabilities

To add the jar files select your project - click on MyEclipse


menu - Project Capabilities - add Hibernate
capabilities- next- next. Now specify the database connection
details as displayed in the figure below.
Here, Check the Enable dynamic table creation check
box to create automatic table - next - Uncheck the create
SessionFactory classbecause we are going to write the code
to get session object self for better understanding - finish.

Now configuration file will be created automatically.

3) Create the Persistent class

Here, we are creating the same persistent class which we have


created in the previous topic. To create the persistent class, Right
click on src - New - Class - specify the class with package name
(e.g. com.javatpoint.mypackage) - finish.
Employee.java
1. package com.javatpoint.mypackage;  
2.   
3. public class Employee {  
4. private int id;  
5. private String firstName,lastName;  
6.   
7. public int getId() {  
8.     return id;  
9. }  
10. public void setId(int id) {  
11.     this.id = id;  
12. }  
13. public String getFirstName() {  
14.     return firstName;  
15. }  
16. public void setFirstName(String firstName) {  
17.     this.firstName = firstName;  
18. }  
19. public String getLastName() {  
20.     return lastName;  
21. }  
22. public void setLastName(String lastName) {  
23.     this.lastName = lastName;  
24. }  
25.   
26.   
27. }  

4) Create the mapping file for Persistent class

Here, we are creating the same mapping file as created in the


previous topic. To create the mapping file, Right click on src -
new - file - specify the file name (e.g. employee.hbm.xml) - ok. It
must be outside the package. Copy the dtd for this mapping file
from this example after downloading it.
employee.hbm.xml
1. <?xml version='1.0' encoding='UTF-8'?>  
2. <!DOCTYPE hibernate-mapping PUBLIC  
3.  "-//Hibernate/Hibernate Mapping DTD 3.0//EN"  
4.  "http://hibernate.sourceforge.net/hibernate-mapping-
3.0.dtd">  
5.   
6.  <hibernate-mapping>  
7.   <class name="com.javatpoint.mypackage.Employee" tabl
e="emp1000">  
8.     <id name="id">  
9.      <generator class="assigned"></generator>  
10.     </id>  
11.             
12.     <property name="firstName"></property>  
13.     <property name="lastName"></property>  
14.             
15.   </class>  
16.             
17.  </hibernate-mapping>  

5) Add mapping of hbm file in configuration file

open the hibernate.cgf.xml file, and add an entry of mapping


resource like this:

1. <mapping resource="employee.hbm.xml"/>  

Now the configuration file will look like this:

hibernate.cfg.xml
1. <?xml version='1.0' encoding='UTF-8'?>  
2. <!DOCTYPE hibernate-configuration PUBLIC  
3.           "-//Hibernate/Hibernate Configuration DTD 3.0//EN"  
4.           "http://hibernate.sourceforge.net/hibernate-
configuration-3.0.dtd">  
5.   
6. <hibernate-configuration>  
7.   
8.     <session-factory>  
9.         <property name="hbm2ddl.auto">update</property>  
10.         <property name="dialect">org.hibernate.dialect.Oracl
e9Dialect</property>  
11.         <property name="connection.url">jdbc:oracle:thin:@l
ocalhost:1521:xe</property>  
12.         <property name="connection.username">system</pr
operty>  
13.         <property name="connection.password">oracle</prop
erty>  
14.         <property name="connection.driver_class">oracle.jdb
c.driver.OracleDriver</property>  
15.     <mapping resource="employee.hbm.xml"/>  
16.     </session-factory>  
17.   
18. </hibernate-configuration>  

6) Create the class that retrieves or stores the persistent object

In this class, we are simply storing the employee object to the


database.

1. package com.javatpoint.mypackage;  
2.   
3. import org.hibernate.Session;  
4. import org.hibernate.SessionFactory;  
5. import org.hibernate.Transaction;  
6. import org.hibernate.cfg.Configuration;  
7.   
8. public class StoreData {  
9. public static void main(String[] args) {  
10.       
11.     //creating configuration object  
12.     Configuration cfg=new Configuration();  
13.     cfg.configure("hibernate.cfg.xml");//populates the data of 
the configuration file  
14.       
15.     //creating seession factory object  
16.     SessionFactory factory=cfg.buildSessionFactory();  
17.       
18.     //creating session object  
19.     Session session=factory.openSession();  
20.       
21.     //creating transaction object  
22.     Transaction t=session.beginTransaction();  
23.           
24.     Employee e1=new Employee();  
25.     e1.setId(115);  
26.     e1.setFirstName("sonoo");  
27.     e1.setLastName("jaiswal");  
28.       
29.     session.persist(e1);//persisting the object  
30.       
31.     t.commit();//transaction is commited  
32.     session.close();  
33.       
34.     System.out.println("successfully saved");  
35.       
36. }  
37. }  

7) Add the jar file for oracle (ojdbc14.jar)

To add the ojdbc14.jar file, right click on your project - build


path - add external archives - select the ojdbc14.jar file - open.

8) Run the application

Before running the application, determine that directory structure


is like this.
To run the hibernate application, right click on the StoreData
class - Run As - Java Application.

Hibernate Example using Annotation in Eclipse


The hibernate application can be created with annotation. There
are many annotations that can be used to create hibernate
application such as @Entity, @Id, @Table etc.

Hibernate Annotations are based on the JPA 2 specification and


supports all the features.

All the JPA annotations are defined in


the javax.persistence package. Hibernate EntityManager
implements the interfaces and life cycle defined by the JPA
specification.

The core advantage of using hibernate annotation is that you


don't need to create mapping (hbm) file. Here, hibernate
annotations are used to provide the meta data.

Example to create the hibernate application with


Annotation
Here, we are going to create a maven based hibernate
application using annotation in eclipse IDE. For creating the
hibernate application in Eclipse IDE, we need to follow the
below steps:

1) Create the Maven Project

o To create the maven project left click on File


Menu - New- Maven Project.
o The new maven project opens in your eclipse. Click Next.
o Now, select catalog type: internal and maven archetype
- quickstart of 1.1 version. Then, click next.
o Now, specify the name of Group Id and Artifact Id. The
Group Id contains package name (e.g. com.javatpoint) and
Artifact Id contains project name (e.g.
HibernateAnnotation). Then click Finish.
2) Add project information and configuration in pom.xml file.

Open pom.xml file and click source. Now, add the below
dependencies between <dependencies>....</dependencies>
tag. These dependencies are used to add the jar files in Maven
project.

1. <dependency>  
2.     <groupId>org.hibernate</groupId>  
3.     <artifactId>hibernate-core</artifactId>  
4.     <version>5.3.1.Final</version>  
5. </dependency>  
6.       
7. <dependency>  
8.     <groupId>com.oracle</groupId>  
9.     <artifactId>ojdbc14</artifactId>  
10.     <version>10.2.0.4.0</version>  
11. </dependency>  

Due to certain license issues, Oracle drivers are not present in


public Maven repository. We can install it manually. To install
Oracle driver into your local Maven repository, follow the
following steps:

o Install Maven
o Run the command : install-file
-Dfile=Path/to/your/ojdbc14.jar -DgroupId=com.oracle
-DartifactId=ojdbc14 -Dversion=12.1.0 -Dpackaging=jar

3) Create the Persistence class.


Here, we are creating the same persistent class which we have
created in the previous topic. But here, we are using
annotation.

@Entity annotation marks this class as an entity.

@Table annotation specifies the table name where data of this


entity is to be persisted. If you don't use @Table annotation,
hibernate will use the class name as the table name by default.

@Id annotation marks the identifier for this entity.

@Column annotation specifies the details of the column for this


property or field. If @Column annotation is not specified,
property name will be used as the column name by default.

To create the Persistence class, right click on src/main/java -


New - Class - specify the class name with package - finish.

Employee.java
package com.javatpoint.mypackage;  
  
import javax.persistence.Entity;  
import javax.persistence.Id;  
import javax.persistence.Table;  
  
@Entity  
@Table(name= "emp500")   
public class Employee {    
  
@Id   
private int id;    
private String firstName,lastName;    
    
public int getId() {    
    return id;    
}    
public void setId(int id) {    
    this.id = id;    
}    
public String getFirstName() {    
    return firstName;    
}    
public void setFirstName(String firstName) {    
    this.firstName = firstName;    
}    
public String getLastName() {    
    return lastName;    
}    
public void setLastName(String lastName) {    
    this.lastName = lastName;    
}    
}   

4) Create the Configuration file

To create the configuration file, right click on src/main/java -


new - file - specify the file name (e.g. hibernate.cfg.xml)
- Finish.

hibernate.cfg.xml

<?xml version="1.0" encoding="UTF-8"?>  
<!DOCTYPE hibernate-configuration PUBLIC  
        "-//Hibernate/Hibernate Configuration DTD 5.3//EN"  
        "http://www.hibernate.org/dtd/hibernate-configuration-
5.3.dtd">  
<hibernate-configuration>  
    <session-factory>  
            
    <property name="hbm2ddl.auto">update</property>    
        <property name="dialect">org.hibernate.dialect.Oracle9Dial
ect</property>    
        <property name="connection.url">jdbc:oracle:thin:@localho
st:1521:xe</property>    
        <property name="connection.username">system</property
>    
        <property name="connection.password">jtp</property>    
        <property name="connection.driver_class">oracle.jdbc.drive
r.OracleDriver</property>   
       
        <mapping class="com.javatpoint.mypackage.Employee"/>  
    </session-factory>  
</hibernate-configuration>  

5) Create the class that retrieves or stores the persistent object.

StoreData.java

package com.javatpoint.mypackage;    
    
import org.hibernate.Session;    
import org.hibernate.SessionFactory;    
import org.hibernate.Transaction;  
import org.hibernate.boot.Metadata;  
import org.hibernate.boot.MetadataSources;  
import org.hibernate.boot.registry.StandardServiceRegistry;  
import org.hibernate.boot.regis
try.StandardServiceRegistryBuilder;  
  
    
public class StoreData {    
public static void main(String[] args) {    
        
    StandardServiceRegistry ssr = new StandardServiceRegistryBui
lder().configure("hibernate.cfg.xml").build();  
    Metadata meta = new MetadataSources(ssr).getMetadataBuild
er().build();  
  
SessionFactory factory = meta.getSessionFactoryBuilder().build(); 
 
Session session = factory.openSession();  
Transaction t = session.beginTransaction();   
            
    Employee e1=new Employee();    
    e1.setId(101);    
    e1.setFirstName("Gaurav");    
    e1.setLastName("Chawla");    
        
    session.save(e1);  
    t.commit();  
    System.out.println("successfully saved");    
    factory.close();  
    session.close();    
        
}    
}   

6) Run the application

Before running the application, determine that the directory


structure is like this.
To run the hibernate application, right click on the StoreData -
Run As - Java Application.

Web Application with Hibernate (using XML)

1. Web Application with Hibernate


2. Example to create web application using hibernate

Here, we are going to create a web application with hibernate. For


creating the web application, we are using JSP for presentation
logic, Bean class for representing data and DAO class for database
codes.

As we create the simple application in hibernate, we don't need to


perform any extra operations in hibernate for creating web
application. In such case, we are getting the value from the user
using the JSP file.

Example to create web application using hibernate


In this example, we are going to insert the record of the user in
the database. It is simply a registration form.

index.jsp

This page gets input from the user and sends it to the register.jsp
file using post method.

1. <form action="register.jsp" method="post">  
2. Name:<input type="text" name="name"/><br><br/>  
3. Password:<input type="password" name="password"/><br
><br/>  
4. Email ID:<input type="text" name="email"/><br><br/>  
5. <input type="submit" value="register"/>"  
6.   
7. </form>  

register.jsp

This file gets all request parameters and stores this information
into an object of User class. Further, it calls the register method
of UserDao class passing the User class object.

<%@page import="com.javatpoint.mypack.UserDao"%>  
<jsp:useBean id="obj" class="com.javatpoint.mypack.User">  
</jsp:useBean>  
<jsp:setProperty property="*" name="obj"/>  
 
<%  
int i=UserDao.register(obj);  
if(i>0)  
out.print("You are successfully registered");  
 
%>  
User.java

It is the simple bean class representing the Persistent class in


hibernate.

package com.javatpoint.mypack;  
 
public class User {  
private int id;  
private String name,password,email;  
 
//getters and setters  
 
}  

user.hbm.xml

It maps the User class with the table of the database.

<?xml version='1.0' encoding='UTF-8'?>  
<!DOCTYPE hibernate-mapping PUBLIC  
"-//Hibernate/Hibernate Mapping DTD 5.3//EN"  
"http://hibernate.sourceforge.net/hibernate-mapping-5.3.dtd">  
 
<hibernate-mapping>  
<class name="com.javatpoint.mypack.User" table="u400">  
<id name="id">  
<generator class="increment"></generator>  
</id>  
<property name="name"></property>  
<property name="password"></property>  
<property name="email"></property>  
</class>  
        
</hibernate-mapping>  

UserDao.java
A Dao class, containing method to store the instance of User
class.

package com.javatpoint.mypack;    
 
import org.hibernate.Session;  
import org.hibernate.SessionFactory;  
import org.hibernate.Transaction;  
import org.hibernate.boot.Metadata;  
import org.hibernate.boot.MetadataSources;  
import org.hibernate.boot.registry.StandardServiceRegistry;  
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;  
  
public class UserDao {    
   
public static int register(User u){    
int i=0;    
 
StandardServiceRegistry ssr = new StandardServiceRegistryBuilder
().configure("hibernate.cfg.xml").build();  
Metadata meta = new MetadataSources(ssr).getMetadataBuilder().
build();  
 
SessionFactory factory = meta.getSessionFactoryBuilder().build();  
Session session = factory.openSession();  
Transaction t = session.beginTransaction();   
 
i=(Integer)session.save(u);    
 
t.commit();    
session.close();    
   
return i;    
  
}    
}    
hibernate.cfg.xml

It is a configuration file, containing informations about the


database and mapping file.

<?xml version='1.0' encoding='UTF-8'?>  
<!DOCTYPE hibernate-configuration PUBLIC  
         "-//Hibernate/Hibernate Configuration DTD 5.3//EN"  
         "http://hibernate.sourceforge.net/hibernate-configuration-
5.3.dtd">  
 
<hibernate-configuration>  
 
<session-factory>  
<property name="hbm2ddl.auto">create</property>  
<property name="dialect">org.hibernate.dialect.Oracle9Dialect</pr
operty>  
<property name="connection.url">jdbc:oracle:thin:@localhost:152
1:xe</property>  
<property name="connection.username">system</property>  
<property name="connection.password">jtp</property>  
<property name="connection.driver_class">oracle.jdbc.driver.Oracl
eDriver</property>  
     
<mapping resource="user.hbm.xml"/>  
</session-factory>  
 

</hibernate-configuration>  

Output
 

Generator classes in Hibernate

1. Hibernate Architecture
2. Hibernate Framework
3. Advantages of Hibernate Framework

The <generator> class is a sub-element of id. It is used to


generate the unique identifier for the objects of persistent class.
There are many generator classes defined in the Hibernate
Framework.
All the generator classes implements
the org.hibernate.id.IdentifierGenerator interface. The
application programmer may create one's own generator classes
by implementing the IdentifierGenerator interface. Hibernate
framework provides many built-in generator classes:

1. assigned
2. increment
3. sequence
4. hilo
5. native
6. identity
7. seqhilo
8. uuid
9. guid
10. select
11. foreign
12. sequence-identity

1) assigned

It is the default generator strategy if there is no <generator>


element . In this case, application assigns the id. For example:

1. ....  
2.  <hibernate-mapping>  
3.   <class ...>  
4.     <id ...>  
5.      <generator class="assigned"></generator>  
6.     </id>  
7.             
8.     .....  
9.             
10.   </class>  
11.  </hibernate-mapping>  

2) increment

It generates the unique id only if no other process is inserting


data into this table. It generates short, int or long type
identifier. If a table contains an identifier then the application
considers its maximum value else the application consider that
the first generated identifier is 1. For each attribute value, the
hibernate increment the identifier by 1. Syntax:

1. ....  
2.  <hibernate-mapping>  
3.   <class ...>  
4.     <id ...>  
5.      <generator class="increment"></generator>  
6.     </id>  
7.             
8.     .....  
9.             
10.   </class>  
11.  </hibernate-mapping>  

3) sequence

It uses the sequence of the database. if there is no sequence


defined, it creates a sequence automatically e.g. in case of Oracle
database, it creates a sequence named HIBERNATE_SEQUENCE.
In case of Oracle, DB2, SAP DB, Postgre SQL or McKoi, it uses
sequence but it uses generator in interbase. Syntax:

1. .....  
2.  <id ...>  
3.   <generator class="sequence"></generator>  
4.  </id>  
5.  .....  
For defining your own sequence, use the param subelement of
generator.

1. .....  
2.  <id ...>  
3.   <generator class="sequence">  
4.       <param name="sequence">your_sequence_name</par
am>  
5.   </generator>  
6.  </id>  
7.  .....  

4) hilo

It uses high and low algorithm to generate the id of type short, int
and long. Syntax:

1. .....  
2.  <id ...>  
3.   <generator class="hilo"></generator>  
4.  </id>  
5.  .....  

5) native

It uses identity, sequence or hilo depending on the database


vendor. Syntax:

1. .....  
2.  <id ...>  
3.   <generator class="native"></generator>  
4.  </id>  
5.  .....  

6) identity
It is used in Sybase, My SQL, MS SQL Server, DB2 and
HypersonicSQL to support the id column. The returned id is of
type short, int or long. It is responsibility of database to generate
unique identifier.

7) seqhilo

It uses high and low algorithm on the specified sequence name.


The returned id is of type short, int or long.

8) uuid

It uses 128-bit UUID algorithm to generate the id. The returned id


is of type String, unique within a network (because IP is used).
The UUID is represented in hexadecimal digits, 32 in length.

9) guid

It uses GUID generated by database of type string. It works on


MS SQL Server and MySQL.

10) select

It uses the primary key returned by the database trigger.

11) foreign

It uses the id of another associated object, mostly used with


<one-to-one> association.
12) sequence-identity

It uses a special sequence generation strategy. It is supported


in Oracle 10g drivers only.

SQL Dialects in Hibernate

The dialect specifies the type of database used in hibernate so


that hibernate generate appropriate type of SQL statements. For
connecting any hibernate application with the database, it is
required to provide the configuration of SQL dialect.

Syntax of SQL Dialect

1. <property name="dialect">org.hibernate.dialect.Oracle9Dial
ect</property>  

List of SQL Dialects

There are many Dialects classes defined for RDBMS in


the org.hibernate.dialect package. They are as follows:

RDBMS Dialect

Oracle (any version) org.hibernate.dialect.OracleDialect

Oracle9i org.hibernate.dialect.Oracle9iDialect

Oracle10g org.hibernate.dialect.Oracle10gDialect
MySQL org.hibernate.dialect.MySQLDialect

MySQL with InnoDB org.hibernate.dialect.MySQLInnoDBDial

MySQL with MyISAM org.hibernate.dialect.MySQLMyISAMDia

DB2 org.hibernate.dialect.DB2Dialect

DB2 AS/400 org.hibernate.dialect.DB2400Dialect

DB2 OS390 org.hibernate.dialect.DB2390Dialect

Microsoft SQL Server org.hibernate.dialect.SQLServerDialect

Sybase org.hibernate.dialect.SybaseDialect

Sybase Anywhere org.hibernate.dialect.SybaseAnywhereD

PostgreSQL org.hibernate.dialect.PostgreSQLDialect

SAP DB org.hibernate.dialect.SAPDBDialect

Informix org.hibernate.dialect.InformixDialect

HypersonicSQL org.hibernate.dialect.HSQLDialect

Ingres org.hibernate.dialect.IngresDialect

Progress org.hibernate.dialect.ProgressDialect

Mckoi SQL org.hibernate.dialect.


MckoiDialect

Interbase org.hibernate.dialect.
InterbaseDialect

Pointbase org.hibernate.dialect.
PointbaseDialect

FrontBase org.hibernate.dialect.
FrontbaseDialect

Firebird org.hibernate.dialect.
FirebirdDialect

Hibernate Logging by Log4j using xml file

1. Hibernate Logging
2. Example of Hibernate Logging

Logging enables the programmer to write the log details into a file
permanently. Log4j and Logback frameworks can be used in
hibernate framework to support logging.

There are two ways to perform logging using log4j:

1. By log4j.xml file (or)


2. By log4j.properties file
Levels of Logging

Following are the common logging levels.

Levels Description

OFF This level is used to turn off logging.

WARNING This is a message level that indicates a problem.

SEVERE This is a message level that indicates a failure.

INFO This level is used for informational messages.

CONFIG This level is used for static configuration messages.

Steps to perform Hibernate Logging by Log4j using xml file

There are two ways to perform logging using log4j using xml file:

1. Load the log4j jar files with hibernate


2. Create the log4j.xml file inside the src folder (parallel with
hibernate.cfg.xml file)

Example of Hibernate Logging by Log4j using xml file

You can enable logging in hibernate by following only two steps in


any hibernate example. This is the first example of hibernate
application with logging support using log4j.
Load the required jar files

You need to load the slf4j.jar and log4j.jar files with hibernate jar
files.

download all the required jar files

Create log4j.xml file

Now you need to create log4j.xml file. In this example, all the log
details will be written in the C:/javatpointlog.log file.

log4j.xml

1. <?xml version="1.0" encoding="UTF-8"?>  
2. <!DOCTYPE log4j:configuration SYSTEM "log4j.dtd">  
3. <log4j:configuration xmlns:log4j="http://jakarta.apache.org
/log4j/"  
4.     debug="false">  
5. <appender name="CONSOLE" class="org.apache.log4j.Cons
oleAppender">  
6.  <layout class="org.apache.log4j.PatternLayout">  
7.   <param name="ConversionPattern" value="[%d{dd/MM/yy 
hh:mm:ss:sss z}] %5p %c{2}: %m%n" />  
8.  </layout>  
9. </appender>  
10.     <appender name="ASYNC" class="org.apache.log4j.Asyn
cAppender">  
11.         <appender-ref ref="CONSOLE" />  
12.         <appender-ref ref="FILE" />  
13. </appender>  
14. <appender name="FILE" class="org.apache.log4j.RollingFile
Appender">  
15.     <param name="File" value="C:/javatpointlog.log" />  
16.     <param name="MaxBackupIndex" value="100" />  
17.  <layout class="org.apache.log4j.PatternLayout">  
18.   <param name="ConversionPattern" value="[%d{dd/MM/yy 
hh:mm:ss:sss z}] %5p %c{2}: %m%n" />  
19. </layout>  
20. </appender>  
21.     <category name="org.hibernate">  
22.         <priority value="DEBUG" />  
23.     </category>  
24.     <category name="java.sql">  
25.         <priority value="debug" />  
26.     </category>  
27.     <root>  
28.         <priority value="INFO" />  
29.         <appender-ref ref="FILE" />  
30.     </root>  
31. </log4j:configuration>  

Hibernate Logging by Log4j using properties file

1. Hibernate Logging
2. Example of Hibernate Logging

As we know, Log4j and Logback frameworks are used to support


logging in hibernate, there are two ways to perform logging using
log4j:

1. By log4j.xml file (or)


2. By log4j.properties file

Here, we are going to enable logging using log4j through


properties file.

Steps to perform Hibernate Logging by Log4j using properties file

There are two ways to perform logging using log4j using


properties file:

1. Load the log4j jar files with hibernate


2. Create the log4j.properties file inside the src folder (parallel
with hibernate.cfg.xml file)

Example of Hibernate Logging by Log4j using properties file

You can enable logging in hibernate by following only two steps in


any hibernate example. This is the first example of hibernate
application with logging support using log4j.

Load the required jar files

You need to load the slf4j.jar and log4j.jar files with hibernate jar
files.

download all the required jar files

Create log4j.properties file

Now you need to create log4j.properties file. In this example, all


the log details will be written in the C:\\javatpointhibernate.log
file.

log4j.properties

1. # Direct log messages to a log file  
2. log4j.appender.file=org.apache.log4j.RollingFileAppender  
3. log4j.appender.file.File=C:\\javatpointhibernate.log  
4. log4j.appender.file.MaxFileSize=1MB  
5. log4j.appender.file.MaxBackupIndex=1  
6. log4j.appender.file.layout=org.apache.log4j.PatternLayout  
7. log4j.appender.file.layout.ConversionPattern=
%d{ABSOLUTE} %5p %c{1}:%L - %m%n  
8.    
9. # Direct log messages to stdout  
10. log4j.appender.stdout=org.apache.log4j.ConsoleAppender  
11. log4j.appender.stdout.Target=System.out  
12. log4j.appender.stdout.layout=org.apache.log4j.PatternLayou
t  
13. log4j.appender.stdout.layout.ConversionPattern=
%d{ABSOLUTE} %5p %c{1}:%L - %m%n  
14.    
15. # Root logger option  
16. log4j.rootLogger=INFO, file, stdout  
17.    
18. # Log everything. Good for troubleshooting  
19. log4j.logger.org.hibernate=INFO  
20.    
21. # Log all JDBC parameters  
22. log4j.logger.org.hibernate.type=ALL  

Hibernate Inheritance Mapping Tutorial


1. Table Per Hierarchy
2. Table Per Concrete class
3. Table Per Subclass

We can map the inheritance hierarchy classes with the table of the database. There are
three inheritance mapping strategies defined in the hibernate:

1. Table Per Hierarchy


2. Table Per Concrete class
3. Table Per Subclass

Table Per Hierarchy

In table per hierarchy mapping, single table is required to map the whole hierarchy, an
extra column (known as discriminator column) is added to identify the class. But nullable
values are stored in the table .

Table Per Hierarchy using xml file


Table Per Hierarchy using Annotation

Table Per Concrete class

In case of table per concrete class, tables are created as per class. But duplicate column is
added in subclass tables.

Table Per Concrete class using xml file


Table Per Concrete class using Annotation

Table Per Subclass

In this strategy, tables are created as per class but related by foreign key. So there are no
duplicate columns.

Table Per Subclass using xml file


Table Per Subclass using Annotation

Hibernate Table Per Hierarchy using xml file


1. Table Per Hierarchy
2. Example of Table Per Hierarchy
By this inheritance strategy, we can map the whole hierarchy by single table only. Here, an
extra column (also known as discriminator column) is created in the table to identify the
class.

Let's understand the problem first. I want to map the whole hierarchy given below into one
table of the database.

There are three classes in this hierarchy. Employee is the super class for Regular_Employee
and Contract_Employee classes. Let's see the mapping file for this hierarchy.

1. <?xml version='1.0' encoding='UTF-8'?>  
2. <!DOCTYPE hibernate-mapping PUBLIC  
3.           "-//Hibernate/Hibernate Mapping DTD 5.3//EN"  
4.           "http://hibernate.sourceforge.net/hibernate-mapping-5.3.dtd">  
5.   
6. <hibernate-mapping>  
7. <class name="com.javatpoint.mypackage.Employee" table="emp121" discriminator
-value="emp">  
8. <id name="id">  
9. <generator class="increment"></generator>  
10. </id>  
11.   
12. <discriminator column="type" type="string"></discriminator>  
13. <property name="name"></property>  
14.             
15. <subclass name="com.javatpoint.mypackage.Regular_Employee" discriminator-
value="reg_emp">  
16. <property name="salary"></property>  
17. <property name="bonus"></property>  
18. </subclass>  
19.             
20. <subclass name="com.javatpoint.mypackage.Contract_Employee" discriminator-
value="con_emp">  
21. <property name="pay_per_hour"></property>  
22. <property name="contract_duration"></property>  
23. </subclass>  
24.             
25. </class>  
26.             
27. </hibernate-mapping>  
In case of table per class hierarchy an discriminator column is added by the hibernate
framework that specifies the type of the record. It is mainly used to distinguish the
record. To specify this, discriminator subelement of class must be specified.

The subclass subelement of class, specifies the subclass. In this case, Regular_Employee


and Contract_Employee are the subclasses of Employee class.

The table structure for this hierarchy is as shown below:


Example of Table per class hierarchy
In this example we are creating the three classes and provide mapping of these classes in
the employee.hbm.xml file.

1) Create the Persistent classes

You need to create the persistent classes representing the inheritance. Let's create the
three classes for the above hierarchy:

File: Employee.java

1. package com.javatpoint.mypackage;  
2.   
3. public class Employee {  
4. private int id;  
5. private String name;  
6.   
7. //getters and setters  
8. }  
File: Regular_Employee.java

1. package com.javatpoint.mypackage;  
2.   
3. public class Regular_Employee extends Employee{  
4. private float salary;  
5. private int bonus;  
6.   
7. //getters and setters  
8. }  
File: Contract_Employee.java

1. package com.javatpoint.mypackage;  
2.   
3. public class Contract_Employee extends Employee{  
4.     private float pay_per_hour;  
5.     private String contract_duration;  
6.   
7. //getters and setters  
8. }  

2) Create the mapping file for Persistent class


The mapping has been discussed above for the hierarchy.

File: employee.hbm.xml

1. <?xml version='1.0' encoding='UTF-8'?>  
2. <!DOCTYPE hibernate-mapping PUBLIC  
3.           "-//Hibernate/Hibernate Mapping DTD 5.3//EN"  
4.           "http://hibernate.sourceforge.net/hibernate-mapping-5.3.dtd">  
5.   
6. <hibernate-mapping>  
7. <class name="com.javatpoint.mypackage.Employee" table="emp121" discriminator
-value="emp">  
8. <id name="id">  
9. <generator class="increment"></generator>  
10. </id>  
11.   
12. <discriminator column="type" type="string"></discriminator>  
13. <property name="name"></property>  
14.             
15. <subclass name="com.javatpoint.mypackage.Regular_Employee" discriminator-
value="reg_emp">  
16. <property name="salary"></property>  
17. <property name="bonus"></property>  
18. </subclass>  
19.             
20. <subclass name="com.javatpoint.mypackage.Contract_Employee" discriminator-
value="con_emp">  
21. <property name="pay_per_hour"></property>  
22. <property name="contract_duration"></property>  
23. </subclass>  
24.             
25. </class>  
26.             
27. </hibernate-mapping>  

3) Add mapping of hbm file in configuration file

Open the hibernate.cgf.xml file, and add an entry of mapping resource like this:

1. <mapping resource="employee.hbm.xml"/>  
Now the configuration file will look like this:

File: hibernate.cfg.xml

1. <?xml version='1.0' encoding='UTF-8'?>  
2. <!DOCTYPE hibernate-configuration PUBLIC  
3.           "-//Hibernate/Hibernate Configuration DTD 5.3//EN"  
4.           "http://hibernate.sourceforge.net/hibernate-configuration-5.3.dtd">  
5.   
6. <hibernate-configuration>  
7.   
8.     <session-factory>  
9.         <property name="hbm2ddl.auto">update</property>  
10.         <property name="dialect">org.hibernate.dialect.Oracle9Dialect</property>  
11.         <property name="connection.url">jdbc:oracle:thin:@localhost:1521:xe</prop
erty>  
12.         <property name="connection.username">system</property>  
13.         <property name="connection.password">jtp</property>  
14.         <property name="connection.driver_class">oracle.jdbc.driver.OracleDriver</pr
operty>  
15.     <mapping resource="employee.hbm.xml"/>  
16.     </session-factory>  
17.   
18. </hibernate-configuration>  

The hbm2ddl.auto property is defined for creating automatic table in the database.

4) Create the class that stores the persistent object

In this class, we are simply storing the employee objects in the database.

File: StoreData.java

1. package com.javatpoint.mypackage;    
2. import org.hibernate.Session;  
3. import org.hibernate.SessionFactory;  
4. import org.hibernate.Transaction;  
5. import org.hibernate.boot.Metadata;  
6. import org.hibernate.boot.MetadataSources;  
7. import org.hibernate.boot.registry.StandardServiceRegistry;  
8. import org.hibernate.boot.registry.StandardServiceRegistryBuilder;  
9.   
10. public class StoreData {    
11. public static void main(String[] args) {    
12.       
13.     StandardServiceRegistry ssr=new StandardServiceRegistryBuilder().configure("hi
bernate.cfg.xml").build();  
14.     Metadata meta=new MetadataSources(ssr).getMetadataBuilder().build();  
15.       
16.     SessionFactory factory=meta.getSessionFactoryBuilder().build();  
17.     Session session=factory.openSession();  
18.     
19.     Transaction t=session.beginTransaction();    
20.         
21.     Employee e1=new Employee();    
22.     e1.setName("Gaurav Chawla");    
23.         
24.     Regular_Employee e2=new Regular_Employee();    
25.     e2.setName("Vivek Kumar");    
26.     e2.setSalary(50000);    
27.     e2.setBonus(5);    
28.         
29.     Contract_Employee e3=new Contract_Employee();    
30.     e3.setName("Arjun Kumar");    
31.     e3.setPay_per_hour(1000);    
32.     e3.setContract_duration("15 hours");    
33.         
34.     session.persist(e1);    
35.     session.persist(e2);    
36.     session.persist(e3);    
37.         
38.     t.commit();    
39.     session.close();    
40.     System.out.println("success");    
41. }    
42. }    

Output:
Hibernate Table Per Hierarchy using Annotation
1. Table Per Hierarchy
2. Example of Table Per Hierarchy

In the previous page, we have mapped the inheritance hierarchy with one table using xml
file. Here, we are going to perform this task using annotation. You need to use
@Inheritance(strategy=InheritanceType.SINGLE_TABLE), @DiscriminatorColumn and
@DiscriminatorValue annotations for mapping table per hierarchy strategy.

In case of table per hierarchy, only one table is required to map the inheritance hierarchy.
Here, an extra column (also known as discriminator column) is created in the table to
identify the class.

Let's see the inheritance hierarchy:

There are three classes in this hierarchy. Employee is the super class for Regular_Employee
and Contract_Employee classes.
The table structure for this hierarchy is as shown below:

Example of Hibernate Table Per Hierarchy using Annotation


You need to follow the following steps to create simple example:

o Create the persistent classes


o Edit pom.xml file
o Create the configuration file
o Create the class to store the fetch the data

1) Create the Persistent classes

You need to create the persistent classes representing the inheritance. Let's create the
three classes for the above hierarchy:

File: Employee.java

package com.javatpoint.mypackage;  
import javax.persistence.*;  
  
@Entity  
@Table(name = "employee101")  
@Inheritance(strategy=InheritanceType.SINGLE_TABLE)  
@DiscriminatorColumn(name="type",discriminatorType=DiscriminatorType.STRING)  
@DiscriminatorValue(value="employee")  
  
public class Employee {  
@Id  
@GeneratedValue(strategy=GenerationType.AUTO)  
      
@Column(name = "id")  
private int id;  
  
@Column(name = "name")  
private String name;  
  
//setters and getters  
}  
File: Regular_Employee.java

package com.javatpoint.mypackage;  
  
import javax.persistence.*;  
  
@Entity  
@DiscriminatorValue("regularemployee")  
public class Regular_Employee extends Employee{  
      
@Column(name="salary")    
private float salary;  
  
@Column(name="bonus")     
private int bonus;  
  
//setters and getters  
}  
File: Contract_Employee.java

package com.javatpoint.mypackage;  
  
import javax.persistence.Column;  
import javax.persistence.DiscriminatorValue;  
import javax.persistence.Entity;  
  
@Entity  
@DiscriminatorValue("contractemployee")  
public class Contract_Employee extends Employee{  
      
    @Column(name="pay_per_hour")  
    private float pay_per_hour;  
      
    @Column(name="contract_duration")  
    private String contract_duration;  
  
    //setters and getters  
}  

2) Add project information and configuration in pom.xml file.


Open pom.xml file and click source. Now, add the below dependencies between
<dependencies>....</dependencies> tag.

1. <dependency>  
2.     <groupId>org.hibernate</groupId>  
3.     <artifactId>hibernate-core</artifactId>  
4.     <version>5.3.1.Final</version>  
5. </dependency>  
6.       
7. <dependency>  
8.     <groupId>com.oracle</groupId>  
9.     <artifactId>ojdbc14</artifactId>  
10.     <version>10.2.0.4.0</version>  
11. </dependency>  

3) Add the persistent classes in configuration file

Open the hibernate.cgf.xml file, and add entries of entity classes like this:

<?xml version="1.0" encoding="UTF-8"?>  
<!DOCTYPE hibernate-configuration PUBLIC  
        "-//Hibernate/Hibernate Configuration DTD 5.3//EN"  
        "http://www.hibernate.org/dtd/hibernate-configuration-5.3.dtd">  
<hibernate-configuration>  
    <session-factory>  
            
    <property name="hbm2ddl.auto">update</property>    
        <property name="dialect">org.hibernate.dialect.Oracle9Dialect</property>    
        <property name="connection.url">jdbc:oracle:thin:@localhost:1521:xe</property>    
        <property name="connection.username">system</property>    
        <property name="connection.password">jtp</property>    
        <property name="connection.driver_class">oracle.jdbc.driver.OracleDriver</property>   
       
        <mapping class="com.javatpoint.mypackage.Employee"/>  
        <mapping class="com.javatpoint.mypackage.Regular_Employee"/>  
        <mapping class="com.javatpoint.mypackage.Contract_Employee"/>  
          
    </session-factory>  
</hibernate-configuration>  

The hbm2ddl.auto property is defined for creating automatic table in the database.

4) Create the class that stores the persistent object

In this class, we are simply storing the employee objects in the database.

File: StoreTest.java

package com.javatpoint.mypackage;  
  
import org.hibernate.Session;  
import org.hibernate.SessionFactory;  
import org.hibernate.Transaction;  
import org.hibernate.boot.Metadata;  
import org.hibernate.boot.MetadataSources;  
import org.hibernate.boot.registry.StandardServiceRegistry;  
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;  
  
public class StoreTest {  
  
    public static void main(String args[])  
    {  
        StandardServiceRegistry ssr = new StandardServiceRegistryBuilder().configure("hibernat
e.cfg.xml").build();  
        Metadata meta = new MetadataSources(ssr).getMetadataBuilder().build();  
          
        SessionFactory factory=meta.getSessionFactoryBuilder().build();  
        Session session=factory.openSession();  
          
         Transaction t=session.beginTransaction();    
            
            Employee e1=new Employee();    
            e1.setName("Gaurav Chawla");    
                
            Regular_Employee e2=new Regular_Employee();    
            e2.setName("Vivek Kumar");    
            e2.setSalary(50000);    
            e2.setBonus(5);    
                
            Contract_Employee e3=new Contract_Employee();    
            e3.setName("Arjun Kumar");    
            e3.setPay_per_hour(1000);    
            e3.setContract_duration("15 hours");    
                
            session.persist(e1);    
            session.persist(e2);    
            session.persist(e3);    
                
            t.commit();    
            session.close();    
            System.out.println("success");        
    }  
}  

Output:

Table Per Concrete class using xml file


1. Table Per Concrete class
2. Example of Table Per Concrete class

In case of Table Per Concrete class, there will be three tables in the database having no
relations to each other. There are two ways to map the table with table per concrete class
strategy.

o By union-subclass element
o By self creating the table for each class
Let's understand what hierarchy we are going to map.

Let's see how can we map this hierarchy by union-subclass element:

1. <?xml version='1.0' encoding='UTF-8'?>  
2. <!DOCTYPE hibernate-mapping PUBLIC  
3.           "-//Hibernate/Hibernate Mapping DTD 5.3//EN"  
4.           "http://hibernate.sourceforge.net/hibernate-mapping-5.3.dtd">  
5.   
6.   <hibernate-mapping>  
7.   <class name="com.javatpoint.mypackage.Employee" table="emp122">  
8.   <id name="id">  
9.   <generator class="increment"></generator>  
10.   </id>  
11.            
12.   <property name="name"></property>  
13.             
14.   <union-subclass name="com.javatpoint.mypackage.Regular_Employee" table
="regemp122">  
15.   <property name="salary"></property>  
16.   <property name="bonus"></property>  
17.   </union-subclass>  
18.             
19.   <union-subclass name="com.javatpoint.mypackage.Contract_Employee" table
="contemp122">  
20.   <property name="pay_per_hour"></property>  
21.   <property name="contract_duration"></property>  
22.   </union-subclass>  
23.             
24.   </class>  
25.             
26.   </hibernate-mapping>  
In case of table per concrete class, there will be three tables in the database, each
representing a particular class.

The union-subclass subelement of class, specifies the subclass. It adds the columns of


parent table into this table. In other words, it is working as a union.

The table structure for each table will be as follows:

Table structure for Employee class

Table structure for Regular_Employee class

 
Table structure for Contract_Employee class

Example of Table per concrete class


In this example we are creating the three classes and provide mapping of these classes in
the employee.hbm.xml file.

1) Create the Persistent classes

You need to create the persistent classes representing the inheritance. Let's create the
three classes for the above hierarchy:

File: Employee.java

1. package com.javatpoint.mypackage;  
2.   
3. public class Employee {  
4. private int id;  
5. private String name;  
6.   
7. //getters and setters  
8. }  
File: Regular_Employee.java

1. package com.javatpoint.mypackage;  
2.   
3. public class Regular_Employee extends Employee{  
4. private float salary;  
5. private int bonus;  
6.   
7. //getters and setters  
8. }  
File: Contract_Employee.java
1. package com.javatpoint.mypackage;  
2.   
3. public class Contract_Employee extends Employee{  
4.     private float pay_per_hour;  
5.     private String contract_duration;  
6.   
7. //getters and setters  
8. }  

2) Create the mapping file for Persistent class

The mapping has been discussed above for the hierarchy.

File: employee.hbm.xml

1. <?xml version='1.0' encoding='UTF-8'?>  
2. <!DOCTYPE hibernate-mapping PUBLIC  
3.           "-//Hibernate/Hibernate Mapping DTD 5.3//EN"  
4.           "http://hibernate.sourceforge.net/hibernate-mapping-5.3.dtd">  
5.   
6.   
7.   <hibernate-mapping>  
8.   <class name="com.javatpoint.mypackage.Employee" table="emp122">  
9.   <id name="id">  
10.   <generator class="increment"></generator>  
11.   </id>  
12.            
13.   <property name="name"></property>  
14.             
15.   <union-subclass name="com.javatpoint.mypackage.Regular_Employee" table
="regemp122">  
16.   <property name="salary"></property>  
17.   <property name="bonus"></property>  
18.   </union-subclass>  
19.             
20.   <union-subclass name="com.javatpoint.mypackage.Contract_Employee" table
="contemp122">  
21.   <property name="pay_per_hour"></property>  
22.   <property name="contract_duration"></property>  
23.   </union-subclass>  
24.             
25.   </class>  
26.             
27.   </hibernate-mapping>  

3) Add mapping of hbm file in configuration file

Open the hibernate.cgf.xml file, and add an entry of mapping resource like this:

1. <mapping resource="employee.hbm.xml"/>  

Now the configuration file will look like this:

File: hibernate.cfg.xml

1. <?xml version='1.0' encoding='UTF-8'?>  
2. <!DOCTYPE hibernate-configuration PUBLIC  
3.           "-//Hibernate/Hibernate Configuration DTD 5.3//EN"  
4.           "http://hibernate.sourceforge.net/hibernate-configuration-5.3.dtd">  
5.   
6. <hibernate-configuration>  
7.   
8.     <session-factory>  
9.         <property name="hbm2ddl.auto">update</property>  
10.         <property name="dialect">org.hibernate.dialect.Oracle9Dialect</property>  
11.         <property name="connection.url">jdbc:oracle:thin:@localhost:1521:xe</prop
erty>  
12.         <property name="connection.username">system</property>  
13.         <property name="connection.password">jtp</property>  
14.         <property name="connection.driver_class">oracle.jdbc.driver.OracleDriver</pr
operty>  
15.     <mapping resource="employee.hbm.xml"/>  
16.     </session-factory>  
17.   
18. </hibernate-configuration>  

The hbm2ddl.auto property is defined for creating automatic table in the database.

4) Create the class that stores the persistent object

In this class, we are simply storing the employee objects in the database.
File: StoreData.java

1. package com.javatpoint.mypackage;  
2.   
3. import org.hibernate.Session;  
4. import org.hibernate.SessionFactory;  
5. import org.hibernate.Transaction;  
6. import org.hibernate.boot.Metadata;  
7. import org.hibernate.boot.MetadataSources;  
8. import org.hibernate.boot.registry.StandardServiceRegistry;  
9. import org.hibernate.boot.registry.StandardServiceRegistryBuilder;  
10.   
11. public class StoreData {  
12.   
13.     public static void main(String[] args) {  
14.   
15.     StandardServiceRegistry ssr=new StandardServiceRegistryBuilder().configure("hi
bernate.cfg.xml").build();  
16.     Metadata meta=new MetadataSources(ssr).getMetadataBuilder().build();  
17.       
18.     SessionFactory factory=meta.getSessionFactoryBuilder().build();  
19.     Session session=factory.openSession();  
20.       
21.     Transaction t=session.beginTransaction();  
22.       
23.     Employee e1=new Employee();    
24.     e1.setName("Gaurav Chawla");    
25.         
26.     Regular_Employee e2=new Regular_Employee();    
27.     e2.setName("Vivek Kumar");    
28.     e2.setSalary(50000);    
29.     e2.setBonus(5);    
30.         
31.     Contract_Employee e3=new Contract_Employee();    
32.     e3.setName("Arjun Kumar");    
33.     e3.setPay_per_hour(1000);    
34.     e3.setContract_duration("15 hours");    
35.         
36.     session.persist(e1);    
37.     session.persist(e2);    
38.     session.persist(e3);    
39.         
40.     t.commit();    
41.     session.close();    
42.     System.out.println("success");    
43. }     
44. }  

Table Per Concrete class using Annotation


1. Table Per Concrete class using annotation

In case of Table Per Concrete class, tables are created per class. So there are no nullable
values in the table. Disadvantage of this approach is that duplicate columns are created in
the subclass tables.

Here, we need to use @Inheritance(strategy = InheritanceType.TABLE_PER_CLASS)


annotation in the parent class and @AttributeOverrides annotation in the subclasses.

@Inheritance(strategy = InheritanceType.TABLE_PER_CLASS) specifies that we are


using table per concrete class strategy. It should be specified in the parent class only.

@AttributeOverrides defines that parent class attributes will be overriden in this class. In


table structure, parent class table columns will be added in the subclass table.

The class hierarchy is given below:


 

The table structure for each table will be as follows:

Table structure for Employee class

Table structure for Regular_Employee class

 
Table structure for Contract_Employee class

Example of Table per concrete class


In this example we are creating the three classes and provide mapping of these classes in
the employee.hbm.xml file.

1) Create the Persistent classes

You need to create the persistent classes representing the inheritance. Let's create the
three classes for the above hierarchy:

File: Employee.java

1. package com.javatpoint.mypackage;  
2. import javax.persistence.*;  
3.   
4. @Entity  
5. @Table(name = "employee102")  
6. @Inheritance(strategy = InheritanceType.TABLE_PER_CLASS)  
7.   
8. public class Employee {  
9. @Id  
10. @GeneratedValue(strategy=GenerationType.AUTO)  
11.       
12. @Column(name = "id")  
13. private int id;  
14.   
15. @Column(name = "name")  
16. private String name;  
17.   
18. //setters and getters  
19. }  
File: Regular_Employee.java
1. package com.javatpoint.mypackage;  
2. import javax.persistence.*;  
3.   
4. @Entity  
5. @Table(name="regularemployee102")  
6. @AttributeOverrides({  
7.     @AttributeOverride(name="id", column=@Column(name="id")),  
8.     @AttributeOverride(name="name", column=@Column(name="name"))  
9. })  
10. public class Regular_Employee extends Employee{  
11.       
12. @Column(name="salary")    
13. private float salary;  
14.   
15. @Column(name="bonus")     
16. private int bonus;  
17.   
18. //setters and getters  
19. }  
File: Contract_Employee.java

1. package com.javatpoint.mypackage;  
2. import javax.persistence.*;  
3. @Entity  
4. @Table(name="contractemployee102")  
5. @AttributeOverrides({  
6.     @AttributeOverride(name="id", column=@Column(name="id")),  
7.     @AttributeOverride(name="name", column=@Column(name="name"))  
8. })  
9. public class Contract_Employee extends Employee{  
10.       
11.     @Column(name="pay_per_hour")  
12.     private float pay_per_hour;  
13.       
14.     @Column(name="contract_duration")  
15.     private String contract_duration;  
16.   
17.     public float getPay_per_hour() {  
18.         return pay_per_hour;  
19.     }  
20.     public void setPay_per_hour(float payPerHour) {  
21.         pay_per_hour = payPerHour;  
22.     }  
23.     public String getContract_duration() {  
24.         return contract_duration;  
25.     }  
26.     public void setContract_duration(String contractDuration) {  
27.         contract_duration = contractDuration;  
28.     }  
29. }  

2) Add project information and configuration in pom.xml file.


Open pom.xml file and click source. Now, add the below dependencies between
<dependencies>....</dependencies> tag.

1. <dependency>  
2.     <groupId>org.hibernate</groupId>  
3.     <artifactId>hibernate-core</artifactId>  
4.     <version>5.3.1.Final</version>  
5. </dependency>  
6.       
7. <dependency>  
8.     <groupId>com.oracle</groupId>  
9.     <artifactId>ojdbc14</artifactId>  
10.     <version>10.2.0.4.0</version>  
11. </dependency>  

3) Add mapping of hbm file in configuration file

File: hibernate.cfg.xml

1. <?xml version='1.0' encoding='UTF-8'?>  
2. <!DOCTYPE hibernate-configuration PUBLIC  
3.           "-//Hibernate/Hibernate Configuration DTD 5.3//EN"  
4.           "http://hibernate.sourceforge.net/hibernate-configuration-5.3.dtd">  
5.   
6. <!-- Generated by MyEclipse Hibernate Tools.                   -->  
7. <hibernate-configuration>  
8.     <session-factory>  
9.         <property name="hbm2ddl.auto">update</property>  
10.         <property name="dialect">org.hibernate.dialect.Oracle9Dialect</property>  
11.         <property name="connection.url">jdbc:oracle:thin:@localhost:1521:xe</prop
erty>  
12.         <property name="connection.username">system</property>  
13.         <property name="connection.password">jtp</property>  
14. <property name="connection.driver_class">oracle.jdbc.driver.OracleDriver</propert
y>  
15.           
16.         <mapping class="com.javatpoint.mypackage.Employee"/>  
17.         <mapping class="com.javatpoint.mypackage.Contract_Employee"/>  
18.         <mapping class="com.javatpoint.mypackage.Regular_Employee"/>  
19.     </session-factory>  
20. </hibernate-configuration>  

The hbm2ddl.auto property is defined for creating automatic table in the database.

4) Create the class that stores the persistent object

In this class, we are simply storing the employee objects in the database.

File: StoreData.java

1. package com.javatpoint.mypackage;  
2.   
3. import org.hibernate.Session;  
4. import org.hibernate.SessionFactory;  
5. import org.hibernate.Transaction;  
6. import org.hibernate.boot.Metadata;  
7. import org.hibernate.boot.MetadataSources;  
8. import org.hibernate.boot.registry.StandardServiceRegistry;  
9. import org.hibernate.boot.registry.StandardServiceRegistryBuilder;  
10.   
11. public class StoreData {  
12.    
13.     public static void main(String[] args) {  
14.       
15.         StandardServiceRegistry ssr=new StandardServiceRegistryBuilder().configure(
"hibernate.cfg.xml").build();  
16.         Metadata meta=new MetadataSources(ssr).getMetadataBuilder().build();  
17.           
18.         SessionFactory factory=meta.getSessionFactoryBuilder().build();  
19.         Session session=factory.openSession();  
20.           
21.         Transaction t=session.beginTransaction();  
22.           
23.         Employee e1=new Employee();  
24.         e1.setName("Gaurav Chawla");  
25.           
26.         Regular_Employee e2=new Regular_Employee();  
27.         e2.setName("Vivek Kumar");  
28.         e2.setSalary(50000);  
29.         e2.setBonus(5);  
30.           
31.         Contract_Employee e3=new Contract_Employee();  
32.         e3.setName("Arjun Kumar");  
33.         e3.setPay_per_hour(1000);  
34.         e3.setContract_duration("15 hours");  
35.           
36.         session.persist(e1);  
37.         session.persist(e2);  
38.         session.persist(e3);  
39.           
40.         t.commit();  
41.         session.close();  
42.         System.out.println("success");        
43.     }  
44. }  

Table Per Subclass Example using xml file


1. Table Per Subclass class
2. Example of Table Per Subclass

In case of Table Per Subclass, subclass mapped tables are related to parent class mapped
table by primary key and foreign key relationship.

The <joined-subclass> element of class is used to map the child class with parent using
the primary key and foreign key relation.

In this example, we are going to use hb2ddl.auto property to generate the table
automatically. So we don't need to be worried about creating tables in the database.

Let's see the hierarchy of classes that we are going to map.


Let's see how can we map this hierarchy by joined-subclass element:

1. <?xml version='1.0' encoding='UTF-8'?>  
2. <!DOCTYPE hibernate-mapping PUBLIC  
3.   
4.   "-//Hibernate/Hibernate Mapping DTD 5.3//EN"  
5.   "http://hibernate.sourceforge.net/hibernate-mapping-5.3.dtd">  
6.   
7.   
8.   <hibernate-mapping>  
9.   <class name="com.javatpoint.mypackage.Employee" table="emp123">  
10.   <id name="id">  
11.   <generator class="increment"></generator>  
12.   </id>  
13.   
14.   <property name="name"></property>  
15.   
16.   <joined-subclass name="com.javatpoint.mypackage.Regular_Employee" table
="regemp123">  
17.   <key column="eid"></key>  
18.   <property name="salary"></property>  
19.   <property name="bonus"></property>  
20.   </joined-subclass>  
21.    
22.   <joined-subclass name="com.javatpoint.mypackage.Contract_Employee" table
="contemp123">  
23.   <key column="eid"></key>  
24.   <property name="pay_per_hour"></property>  
25.   <property name="contract_duration"></property>  
26.   </joined-subclass>  
27.   
28.   </class>  
29.   </hibernate-mapping>  

In case of table per subclass class, there will be three tables in the database, each
representing a particular class.

The joined-subclass subelement of class, specifies the subclass.

The key sub-element of joined-subclass is used to generate the foreign key in the subclass


mapped table. This foreign key will be associated with the primary key of parent class
mapped table.

The table structure for each table will be as follows:

Table structure for Employee class

Table structure for Regular_Employee class

 
Table structure for Contract_Employee class

Example of Table per subclass class


In this example we are creating the three classes and provide mapping of these classes in
the employee.hbm.xml file.

1) Create the Persistent classes

You need to create the persistent classes representing the inheritance. Let's create the
three classes for the above hierarchy:

File: Employee.java

1. package com.javatpoint.mypackage;  
2.   
3. public class Employee {  
4. private int id;  
5. private String name;  
6.   
7. //getters and setters  
8. }  
File: Regular_Employee.java

1. package com.javatpoint.mypackage;  
2. public class Regular_Employee extends Employee{  
3. private float salary;  
4. private int bonus;  
5.   
6. //getters and setters  
7. }  
File: Contract_Employee.java

1. package com.javatpoint.mypackage;  
2.   
3. public class Contract_Employee extends Employee{  
4.     private float pay_per_hour;  
5.     private String contract_duration;  
6.   
7. //getters and setters  
8. }  

2) Create the mapping file for Persistent class

The mapping has been discussed above for the hierarchy.

File: employee.hbm.xml

1. <?xml version='1.0' encoding='UTF-8'?>  
2. <!DOCTYPE hibernate-mapping PUBLIC  
3.   
4.   "-//Hibernate/Hibernate Mapping DTD 5.3//EN"  
5.   "http://hibernate.sourceforge.net/hibernate-mapping-5.3.dtd">  
6.   
7.   
8.   <hibernate-mapping>  
9.   <class name="com.javatpoint.mypackage.Employee" table="emp123">  
10.   <id name="id">  
11.   <generator class="increment"></generator>  
12.   </id>  
13.   
14.   <property name="name"></property>  
15.   
16.   <joined-subclass name="com.javatpoint.mypackage.Regular_Employee" table
="regemp123">  
17.   <key column="eid"></key>  
18.   <property name="salary"></property>  
19.   <property name="bonus"></property>  
20.   </joined-subclass>  
21.    
22.   <joined-subclass name="com.javatpoint.mypackage.Contract_Employee" table
="contemp123">  
23.   <key column="eid"></key>  
24.   <property name="pay_per_hour"></property>  
25.   <property name="contract_duration"></property>  
26.   </joined-subclass>  
27.   
28.   </class>  
29.   </hibernate-mapping>  

3) create configuration file

Open the hibernate.cgf.xml file, and add an entry of mapping resource like this:

1. <mapping resource="employee.hbm.xml"/>  

Now the configuration file will look like this:

File: hibernate.cfg.xml

1. <?xml version='1.0' encoding='UTF-8'?>  
2. <!DOCTYPE hibernate-configuration PUBLIC  
3.           "-//Hibernate/Hibernate Configuration DTD 5.3//EN"  
4.           "http://hibernate.sourceforge.net/hibernate-configuration-5.3.dtd">  
5.   
6. <hibernate-configuration>  
7.   
8.     <session-factory>  
9.         <property name="hbm2ddl.auto">update</property>  
10.         <property name="dialect">org.hibernate.dialect.Oracle9Dialect</property>  
11.         <property name="connection.url">jdbc:oracle:thin:@localhost:1521:xe</prop
erty>  
12.         <property name="connection.username">system</property>  
13.         <property name="connection.password">jtp</property>  
14.         <property name="connection.driver_class">oracle.jdbc.driver.OracleDriver</pr
operty>  
15.     <mapping resource="employee.hbm.xml"/>  
16.     </session-factory>  
17.   
18. </hibernate-configuration>  

The hbm2ddl.auto property is defined for creating automatic table in the database.

4) Create the class that stores the persistent object

In this class, we are simply storing the employee objects in the database.
File: StoreData.java

1. package com.javatpoint.mypackage;  
2.   
3. import org.hibernate.Session;  
4. import org.hibernate.SessionFactory;  
5. import org.hibernate.Transaction;  
6. import org.hibernate.boot.Metadata;  
7. import org.hibernate.boot.MetadataSources;  
8. import org.hibernate.boot.registry.StandardServiceRegistry;  
9. import org.hibernate.boot.registry.StandardServiceRegistryBuilder;  
10.   
11. public class StoreData {  
12. public static void main(String[] args) {  
13.           
14. StandardServiceRegistry ssr=new StandardServiceRegistryBuilder().configure("hiber
nate.cfg.xml").build();  
15. Metadata meta=new MetadataSources(ssr).getMetadataBuilder().build();  
16.   
17. SessionFactory factory=meta.buildSessionFactory();  
18. Session session=factory.openSession();  
19.   
20. Transaction t=session.beginTransaction();    
21.   
22. Employee e1=new Employee();    
23. e1.setName("Gaurav Chawla");    
24.     
25. Regular_Employee e2=new Regular_Employee();    
26. e2.setName("Vivek Kumar");    
27. e2.setSalary(50000);    
28. e2.setBonus(5);    
29.     
30. Contract_Employee e3=new Contract_Employee();    
31. e3.setName("Arjun Kumar");    
32. e3.setPay_per_hour(1000);    
33. e3.setContract_duration("15 hours");    
34.     
35. session.persist(e1);    
36. session.persist(e2);    
37. session.persist(e3);    
38.     
39. t.commit();    
40. session.close();    
41. System.out.println("success");    
42.   
43. }  
44. }  

Table Per Subclass using Annotation


1. Table Per Subclass class
2. Example of Table Per Subclass

As we have specified earlier, in case of table per subclass strategy, tables are created as per
persistent classes but they are treated using primary and foreign key. So there will not be
any duplicate column in the relation.

We need to specify @Inheritance(strategy=InheritanceType.JOINED) in the parent


class and @PrimaryKeyJoinColumn annotation in the subclasses.

Let's see the hierarchy of classes that we are going to map.

 
The table structure for each table will be as follows:

Table structure for Employee class

Table structure for Regular_Employee class

Table structure for Contract_Employee class

Example of Table per subclass class using Annotation


In this example we are creating the three classes and provide mapping of these classes in
the employee.hbm.xml file.

1) Create the Persistent classes

You need to create the persistent classes representing the inheritance. Let's create the
three classes for the above hierarchy:

File: Employee.java
1. package com.javatpoint.mypackage;  
2. import javax.persistence.*;  
3.   
4. @Entity  
5. @Table(name = "employee103")  
6. @Inheritance(strategy=InheritanceType.JOINED)  
7.   
8. public class Employee {  
9. @Id  
10. @GeneratedValue(strategy=GenerationType.AUTO)  
11.       
12. @Column(name = "id")  
13. private int id;  
14.   
15. @Column(name = "name")  
16. private String name;  
17.   
18. //setters and getters  
19. }  
File: Regular_Employee.java

1. package com.javatpoint.mypackage;  
2.   
3. import javax.persistence.*;  
4.   
5. @Entity  
6. @Table(name="regularemployee103")  
7. @PrimaryKeyJoinColumn(name="ID")  
8. public class Regular_Employee extends Employee{  
9.       
10. @Column(name="salary")    
11. private float salary;  
12.   
13. @Column(name="bonus")     
14. private int bonus;  
15.   
16. //setters and getters  
17. }  
File: Contract_Employee.java

1. package com.javatpoint.mypackage;  
2.   
3. import javax.persistence.*;  
4.   
5. @Entity  
6. @Table(name="contractemployee103")  
7. @PrimaryKeyJoinColumn(name="ID")  
8. public class Contract_Employee extends Employee{  
9.       
10.     @Column(name="pay_per_hour")  
11.     private float pay_per_hour;  
12.       
13.     @Column(name="contract_duration")  
14.     private String contract_duration;  
15.   
16.     //setters and getters  
17. }  

2) Add project information and configuration in pom.xml file.


Open pom.xml file and click source. Now, add the below dependencies between
<dependencies>....</dependencies> tag.

1. <dependency>  
2.     <groupId>org.hibernate</groupId>  
3.     <artifactId>hibernate-core</artifactId>  
4.     <version>5.3.1.Final</version>  
5. </dependency>  
6.       
7. <dependency>  
8.     <groupId>com.oracle</groupId>  
9.     <artifactId>ojdbc14</artifactId>  
10.     <version>10.2.0.4.0</version>  
11. </dependency>  

3)Create the configuration file

Open the hibernate.cgf.xml file, and add an entry of mapping resource like this:

1. <mapping class="com.javatpoint.mypackage.Employee"/>  
2. <mapping class="com.javatpoint.mypackage.Contract_Employee"/>  
3. <mapping class="com.javatpoint.mypackage.Regular_Employee"/>  
Now the configuration file will look like this:

File: hibernate.cfg.xml

1. <?xml version='1.0' encoding='UTF-8'?>  
2. <!DOCTYPE hibernate-configuration PUBLIC  
3.           "-//Hibernate/Hibernate Configuration DTD 5.3//EN"  
4.           "http://hibernate.sourceforge.net/hibernate-configuration-5.3.dtd">  
5.   
6. <!-- Generated by MyEclipse Hibernate Tools.                   -->  
7. <hibernate-configuration>  
8.   
9.     <session-factory>  
10.         <property name="hbm2ddl.auto">update</property>  
11.         <property name="dialect">org.hibernate.dialect.Oracle9Dialect</property>  
12.         <property name="connection.url">jdbc:oracle:thin:@localhost:1521:xe</prop
erty>  
13.         <property name="connection.username">system</property>  
14.         <property name="connection.password">jtp</property>  
15. <property name="connection.driver_class">oracle.jdbc.driver.OracleDriver</propert
y>  
16.           
17.         <mapping class="com.javatpoint.mypackage.Employee"/>  
18.         <mapping class="com.javatpoint.mypackage.Contract_Employee"/>  
19.         <mapping class="com.javatpoint.mypackage.Regular_Employee"/>  
20.     </session-factory>  
21.   
22. </hibernate-configuration>  

The hbm2ddl.auto property is defined for creating automatic table in the database.

3) Create the class that stores the persistent object

In this class, we are simply storing the employee objects in the database.

File: StoreData.java

1. package com.javatpoint.mypackage;  
2.   
3. import org.hibernate.Session;  
4. import org.hibernate.SessionFactory;  
5. import org.hibernate.Transaction;  
6. import org.hibernate.boot.Metadata;  
7. import org.hibernate.boot.MetadataSources;  
8. import org.hibernate.boot.registry.StandardServiceRegistry;  
9. import org.hibernate.boot.registry.StandardServiceRegistryBuilder;  
10.   
11. public class StoreData {  
12.   
13.     public static void main(String args[])  
14.     {  
15.         StandardServiceRegistry ssr = new StandardServiceRegistryBuilder().configure
("hibernate.cfg.xml").build();  
16.         Metadata meta = new MetadataSources(ssr).getMetadataBuilder().build();  
17.           
18.         SessionFactory factory=meta.getSessionFactoryBuilder().build();  
19.         Session session=factory.openSession();  
20.           
21.          Transaction t=session.beginTransaction();    
22.             
23.             Employee e1=new Employee();    
24.             e1.setName("Gaurav Chawla");    
25.                 
26.             Regular_Employee e2=new Regular_Employee();    
27.             e2.setName("Vivek Kumar");    
28.             e2.setSalary(50000);    
29.             e2.setBonus(5);    
30.                 
31.             Contract_Employee e3=new Contract_Employee();    
32.             e3.setName("Arjun Kumar");    
33.             e3.setPay_per_hour(1000);    
34.             e3.setContract_duration("15 hours");    
35.                 
36.             session.persist(e1);    
37.             session.persist(e2);    
38.             session.persist(e3);    
39.                 
40.             t.commit();    
41.             session.close();    
42.             System.out.println("success");        
43.     }  
44. }  
Collection Mapping in Hibernate
1. Collection Mapping in Hibernate
2. Mapping collection in mapping file
3. Understanding key element
4. Indexed collections
5. Collection Elements

We can map collection elements of Persistent class in Hibernate. You need to declare the
type of collection in Persistent class from one of the following types:

o java.util.List
o java.util.Set
o java.util.SortedSet
o java.util.Map
o java.util.SortedMap
o java.util.Collection
o or write the implementation of org.hibernate.usertype.UserCollectionType

The persistent class should be defined like this for collection element.

1. package com.javatpoint;  
2.   
3. import java.util.List;  
4.   
5. public class Question {  
6. private int id;  
7. private String qname;  
8. private List<String> answers;//List can be of any type  
9.   
10. //getters and setters  
11.   
12. }  

Mapping collection in mapping file


There are many subelements of <class> elements to map the collection. They
are <list>, <bag>, <set> and <map>. Let's see how we implement the list for the above
class:

1. <class name="com.javatpoint.Question" table="q100">  
2.           <id name="id">  
3.           <generator class="increment"></generator>  
4.           </id>  
5.           <property name="qname"></property>  
6.             
7.           <list name="answers" table="ans100">  
8.           <key column="qid"></key>  
9.           <index column="type"></index>  
10.           <element column="answer" type="string"></element>  
11.           </list>  
12.             
13.           </class>  

There are three subelements used in the list:

o <key> element is used to define the foreign key in this table based on the Question
class identifier.
o <index> element is used to identify the type. List and Map are indexed collection.
o <element> is used to define the element of the collection.

This is the mapping of collection if collection stores string objects. But if collection stores
entity reference (another class objects), we need to define <one-to-many> or <many-to-
many> element. Now the Persistent class will look like:

1. package com.javatpoint;  
2.   
3. import java.util.List;  
4.   
5. public class Question {  
6. private int id;  
7. private String qname;  
8. private List<Answer> answers;//Here, List stores the objects of Answer class  
9.   
10. //getters and setters  
11.   
12. }  
1. package com.javatpoint;  
2. import java.util.List;  
3. public class Answer {  
4. private int id;  
5. private String answer;  
6. private String posterName;  
7. //getters and setters  
8. }  

Now the mapping file will be:

1. <class name="com.javatpoint.Question" table="q100">  
2.           <id name="id">  
3.           <generator class="increment"></generator>  
4.           </id>  
5.           <property name="qname"></property>  
6.             
7.           <list name="answers" >  
8.           <key column="qid"></key>  
9.           <index column="type"></index>  
10.           <one-to-many class="com.javatpoint.Answer" />  
11.           </list>  
12.             
13.           </class>  

Here, List is mapped by one-to-many relation. In this scenario, there can be many answers
for one question.

Understanding key element


The key element is used to define the foreign key in the joined table based on the original
identity. The foreign key element is nullable by default. So for non-nullable foreign key, we
need to specify not-null attribute such as:

1. <key column="qid" not-null="true" ></key>  

The attributes of the key element are column, on-delete, property-ref, not-null, update and
unique.

1. <key  
2. column="columnname"  
3. on-delete="noaction|cascade"  
4. not-null="true|false"  
5. property-ref="propertyName"  
6. update="true|false"  
7. unique="true|false"  
8. />  

Indexed collections
The collection elements can be categorized in two forms:

o indexed ,and
o non-indexed

The List and Map collection are indexed whereas set and bag collections are non-indexed.
Here, indexed collection means List and Map requires an additional element <index>.

Collection Elements
The collection elements can have value or entity reference (another class object). We can
use one of the 4 elements

o element
o component-element
o one-to-many, or
o many-to-many

The element and component-element are used for normal value such as string, int etc.
whereas one-to-many and many-to-many are used to map entity reference.

Upcoming topics in Collection Mapping


Mapping List

In this example, we are going to map the List element.

Mapping Bag

In this example, we are going to use the bag collection of Hibernate framework.
Mapping Set

Here, we will map the set element of collection.

Mapping List in Collection Mapping (using xml file)


1. Mapping List in Collection Mapping
2. Example of mapping list in collection mapping

If our persistent class has List object, we can map the List easily either by <list> element of
class in mapping file or by annotation.

Here, we are using the scenario of Forum where one question has multiple answers.

Let's see how we can implement the list in the mapping file:

1. <class name="com.javatpoint.Question" table="q100">  
2.        ...        
3.           <list name="answers" table="ans100">  
4.           <key column="qid"></key>  
5.           <index column="type"></index>  
6.           <element column="answer" type="string"></element>  
7.           </list>  
8.             
9.        ...  
10. </class>  

List and Map are index based collection, so an extra column will be created in the table for indexing.

Example of mapping list in collection mapping


In this example, we are going to see full example of collection mapping by list. This is the
example of List that stores string value not entity reference that is why we are going to
use element instead of one-to-many within the list element.

1) Create the Persistent class


This persistent class defines properties of the class including List.

1. package com.javatpoint;  
2.   
3. import java.util.List;  
4.   
5. public class Question {  
6. private int id;  
7. private String qname;  
8. private List<String> answers;  
9.   
10. //getters and setters  
11.   
12. }  

2) Create the Mapping file for the persistent class


Here, we have created the question.hbm.xml file for defining the list.

1. <?xml version='1.0' encoding='UTF-8'?>  
2. <!DOCTYPE hibernate-mapping PUBLIC  
3.           "-//Hibernate/Hibernate Mapping DTD 5.3//EN"  
4.           "http://hibernate.sourceforge.net/hibernate-mapping-5.3.dtd">  
5.   
6. <hibernate-mapping>  
7.  <class name="com.javatpoint.Question" table="q100">  
8.    <id name="id">  
9.      <generator class="increment"></generator>  
10.    </id>  
11.    <property name="qname"></property>  
12.             
13.    <list name="answers" table="ans100">  
14.      <key column="qid"></key>  
15.      <index column="type"></index>  
16.      <element column="answer" type="string"></element>  
17.    </list>  
18.             
19.  </class>  
20.             
21. </hibernate-mapping>  

3) Create the configuration file


This file contains information about the database and mapping file.

1. <?xml version='1.0' encoding='UTF-8'?>  
2. <!DOCTYPE hibernate-configuration PUBLIC  
3.           "-//Hibernate/Hibernate Configuration DTD 5.3//EN"  
4.           "http://hibernate.sourceforge.net/hibernate-configuration-5.3.dtd">  
5.   
6. <hibernate-configuration>  
7.   
8.     <session-factory>  
9.         <property name="hbm2ddl.auto">update</property>  
10.         <property name="dialect">org.hibernate.dialect.Oracle9Dialect</property>  
11.         <property name="connection.url">jdbc:oracle:thin:@localhost:1521:xe</prop
erty>  
12.         <property name="connection.username">system</property>  
13.         <property name="connection.password">jtp</property>  
14.         <property name="connection.driver_class">oracle.jdbc.driver.OracleDriver</pr
operty>  
15.     <mapping resource="question.hbm.xml"/>  
16.     </session-factory>  
17.   
18. </hibernate-configuration>  

4) Create the class to store the data


In this class we are storing the data of the question class.

1. package com.javatpoint;    
2.     
3. import java.util.ArrayList;    
4.     
5. import org.hibernate.*;  
6. import org.hibernate.boot.Metadata;  
7. import org.hibernate.boot.MetadataSources;  
8. import org.hibernate.boot.registry.StandardServiceRegistry;  
9. import org.hibernate.boot.registry.StandardServiceRegistryBuilder;  
10.       
11. public class StoreData {    
12.  public static void main(String[] args) {    
13.       
14.      StandardServiceRegistry ssr=new StandardServiceRegistryBuilder().configure("hi
bernate.cfg.xml").build();  
15.         Metadata meta=new MetadataSources(ssr).getMetadataBuilder().build();  
16.           
17.         SessionFactory factory=meta.getSessionFactoryBuilder().build();  
18.         Session session=factory.openSession();  
19.        
20.     Transaction t=session.beginTransaction();    
21.         
22.     ArrayList<String> list1=new ArrayList<String>();    
23.     list1.add("Java is a programming language");    
24.     list1.add("Java is a platform");    
25.         
26.     ArrayList<String> list2=new ArrayList<String>();    
27.     list2.add("Servlet is an Interface");    
28.     list2.add("Servlet is an API");    
29.         
30.     Question question1=new Question();    
31.     question1.setQname("What is Java?");    
32.     question1.setAnswers(list1);    
33.         
34.     Question question2=new Question();    
35.     question2.setQname("What is Servlet?");    
36.     question2.setAnswers(list2);    
37.         
38.     session.persist(question1);    
39.     session.persist(question2);    
40.         
41.     t.commit();    
42.     session.close();    
43.     System.out.println("success");    
44.  }    
45. }    
Output

How to fetch the data of List


Here, we have used HQL to fetch all the records of Question class including answers. In
such case, it fetches the data from two tables that are functional dependent.

1. package com.javatpoint;    
2.     
3. import javax.persistence.TypedQuery;  
4. import java.util.*;  
5. import org.hibernate.*;  
6. import org.hibernate.boot.Metadata;  
7. import org.hibernate.boot.MetadataSources;  
8. import org.hibernate.boot.registry.StandardServiceRegistry;  
9. import org.hibernate.boot.registry.StandardServiceRegistryBuilder;  
10.     
11. public class FetchData {    
12. public static void main(String[] args) {    
13.         
14.     StandardServiceRegistry ssr=new StandardServiceRegistryBuilder().configure("hi
bernate.cfg.xml").build();  
15.     Metadata meta=new MetadataSources(ssr).getMetadataBuilder().build();  
16.       
17.     SessionFactory factory=meta.getSessionFactoryBuilder().build();  
18.     Session session=factory.openSession();  
19.         
20.     TypedQuery query=session.createQuery("from Question");    
21.     List<Question> list=query.getResultList();   
22.         
23.     Iterator<Question> itr=list.iterator();    
24.     while(itr.hasNext()){    
25.         Question q=itr.next();    
26.         System.out.println("Question Name: "+q.getQname());    
27.             
28.         //printing answers    
29.         List<String> list2=q.getAnswers();    
30.         Iterator<String> itr2=list2.iterator();    
31.         while(itr2.hasNext()){    
32.             System.out.println(itr2.next());    
33.         }          
34.     }    
35.     session.close();    
36.     System.out.println("success");         
37. }    
38. }    

Output

Mapping Bag in Collection Mapping (using xml


file)
1. Mapping Bag in Collection Mapping
2. Example of mapping Bag in Collection Mapping

If our persistent class has List object, we can map the List by list or bag element in the
mapping file. The bag is just like List but it doesn't require index element.

Here, we are using the scenario of Forum where one question has multiple answers.
Let's see how we can implement the bag in the mapping file:

1. <class name="com.javatpoint.Question" table="q100">  
2.        ...        
3.           <bag name="answers" table="ans100">  
4.           <key column="qid"></key>  
5.           <element column="answer" type="string"></element>  
6.           </bag>  
7.             
8.        ...  
9. </class>  

Example of mapping bag in collection mapping


In this example, we are going to see full example of collection mapping by bag. This is the
example of bag if it stores value not entity reference that is why are going to
use element instead of one-to-many. If you have seen the example of mapping list, it is
same in all cases instead mapping file where we are using bag instead of list.

1) Create the Persistent class


This persistent class defines properties of the class including List.

1. package com.javatpoint;  
2.   
3. import java.util.List;  
4.   
5. public class Question {  
6. private int id;  
7. private String qname;  
8. private List<String> answers;  
9.   
10. //getters and setters  
11.   
12. }  

2) Create the Mapping file for the persistent class


Here, we have created the question.hbm.xml file for defining the list.

1. <?xml version='1.0' encoding='UTF-8'?>  
2. <!DOCTYPE hibernate-mapping PUBLIC  
3.           "-//Hibernate/Hibernate Mapping DTD 5.3//EN"  
4.           "http://hibernate.sourceforge.net/hibernate-mapping-5.3.dtd">  
5.   
6. <hibernate-mapping>  
7.  <class name="com.javatpoint.Question" table="q101">  
8.    <id name="id">  
9.      <generator class="increment"></generator>  
10.    </id>  
11.    <property name="qname"></property>  
12.             
13.    <bag name="answers" table="ans101">  
14.      <key column="qid"></key>  
15.      <element column="answer" type="string"></element>  
16.    </bag>  
17.             
18.  </class>  
19.             
20. </hibernate-mapping>  

3) Create the configuration file


This file contains information about the database and mapping file.

1. <?xml version='1.0' encoding='UTF-8'?>  
2. <!DOCTYPE hibernate-configuration PUBLIC  
3.           "-//Hibernate/Hibernate Configuration DTD 5.3//EN"  
4.           "http://hibernate.sourceforge.net/hibernate-configuration-5.3.dtd">  
5.   
6. <!-- Generated by MyEclipse Hibernate Tools.                   -->  
7. <hibernate-configuration>  
8.   
9.     <session-factory>  
10.         <property name="hbm2ddl.auto">update</property>  
11.         <property name="dialect">org.hibernate.dialect.Oracle9Dialect</property>  
12.         <property name="connection.url">jdbc:oracle:thin:@localhost:1521:xe</prop
erty>  
13.         <property name="connection.username">system</property>  
14.         <property name="connection.password">jtp</property>  
15.         <property name="connection.driver_class">oracle.jdbc.driver.OracleDriver</pr
operty>  
16.     <mapping resource="question.hbm.xml"/>  
17.     </session-factory>  
18.   
19. </hibernate-configuration>  

4) Create the class to store the data


In this class we are storing the data of the question class.

1. package com.javatpoint;    
2.     
3. import java.util.ArrayList;    
4.   
5. import org.hibernate.Session;  
6. import org.hibernate.SessionFactory;  
7. import org.hibernate.Transaction;  
8. import org.hibernate.boot.Metadata;  
9. import org.hibernate.boot.MetadataSources;  
10. import org.hibernate.boot.registry.StandardServiceRegistry;  
11. import org.hibernate.boot.registry.StandardServiceRegistryBuilder;  
12.     
13. public class StoreData {    
14.  public static void main(String[] args) {    
15.       
16.      StandardServiceRegistry ssr=new StandardServiceRegistryBuilder().configure("hi
bernate.cfg.xml").build();  
17.      Metadata meta=new MetadataSources(ssr).getMetadataBuilder().build();  
18.        
19.      SessionFactory factory=meta.buildSessionFactory();  
20.      Session session=factory.openSession();  
21.        
22.     Transaction t=session.beginTransaction();    
23.         
24.     ArrayList<String> list1=new ArrayList<String>();    
25.     list1.add("Java is a programming language");    
26.     list1.add("Java is a platform");    
27.         
28.     ArrayList<String> list2=new ArrayList<String>();    
29.     list2.add("Servlet is an Interface");    
30.     list2.add("Servlet is an API");    
31.         
32.     Question question1=new Question();    
33.     question1.setQname("What is Java?");    
34.     question1.setAnswers(list1);    
35.         
36.     Question question2=new Question();    
37.     question2.setQname("What is Servlet?");    
38.     question2.setAnswers(list2);    
39.         
40.     session.persist(question1);    
41.     session.persist(question2);    
42.         
43.     t.commit();    
44.     session.close();    
45.     System.out.println("success");    
46.  }    
47. }    

Output

How to fetch the data


Here, we have used HQL to fetch all the records of Question class including answers. In
such case, it fetches the data from two tables that are functional dependent.

1. package com.javatpoint;    
2.     
3. import javax.persistence.TypedQuery;  
4. import java.util.*;  
5. import org.hibernate.*;  
6. import org.hibernate.boot.Metadata;  
7. import org.hibernate.boot.MetadataSources;  
8. import org.hibernate.boot.registry.StandardServiceRegistry;  
9. import org.hibernate.boot.registry.StandardServiceRegistryBuilder;    
10.   
11.     
12. public class FetchData {    
13. public static void main(String[] args) {    
14.         
15.     StandardServiceRegistry ssr=new StandardServiceRegistryBuilder().configure("hi
bernate.cfg.xml").build();  
16.      Metadata meta=new MetadataSources(ssr).getMetadataBuilder().build();  
17.        
18.      SessionFactory factory=meta.buildSessionFactory();  
19.      Session session=factory.openSession();  
20.         
21.     TypedQuery query=session.createQuery("from Question");    
22.     List<Question> list=query.getResultList();    
23.         
24.     Iterator<Question> itr=list.iterator();    
25.     while(itr.hasNext()){    
26.         Question q=itr.next();    
27.         System.out.println("Question Name: "+q.getQname());    
28.             
29.         //printing answers    
30.         List<String> list2=q.getAnswers();    
31.         Iterator<String> itr2=list2.iterator();    
32.         while(itr2.hasNext()){    
33.             System.out.println(itr2.next());    
34.         }    
35.             
36.     }    
37.     session.close();    
38.     System.out.println("success");    
39.         
40. }    
41. }    
Output

Hibernate Mapping Set using XML


1. Mapping Set in Collection Mapping
2. Example of mapping Set in Collection Mapping

If our persistent class has Set object, we can map the Set by set element in the mapping
file. The set element doesn't require index element. The one difference between List and Set
is that, it stores only unique values.

Let's see how we can implement the set in the mapping file:

1. <class name="com.javatpoint.Question" table="q1002">  
2.        ...        
3.           <set name="answers" table="ans1002">  
4.           <key column="qid"></key>  
5.           <element column="answer" type="string"></element>  
6.           </set>  
7.             
8.        ...  
9. </class>  

Example of mapping set in collection mapping


In this example, we are going to see full example of collection mapping by set. This is the
example of set that stores value not entity reference that is why are going to use element
instead of one-to-many.

1) Create the Persistent class


This persistent class defines properties of the class including Set.

1. package com.javatpoint;  
2.   
3. import java.util.Set;  
4.   
5. public class Question {  
6. private int id;  
7. private String qname;  
8. private Set<String> answers;  
9.   
10. //getters and setters  
11.   
12. }  

2) Create the Mapping file for the persistent class


Here, we have created the question.hbm.xml file for defining the list.

1. <?xml version='1.0' encoding='UTF-8'?>  
2. <!DOCTYPE hibernate-mapping PUBLIC  
3.           "-//Hibernate/Hibernate Mapping DTD 5.3//EN"  
4.           "http://hibernate.sourceforge.net/hibernate-mapping-5.3.dtd">  
5.   
6. <hibernate-mapping>  
7.  <class name="com.javatpoint.Question" table="q1002">  
8.    <id name="id">  
9.      <generator class="increment"></generator>  
10.    </id>  
11.    <property name="qname"></property>  
12.             
13.    <set name="answers" table="ans1002">  
14.      <key column="qid"></key>  
15.      <element column="answer" type="string"></element>  
16.    </set>  
17.             
18.  </class>  
19.             
20. </hibernate-mapping>  
3) create the configuration file
This file contains information about the database and mapping file.

1. <?xml version='1.0' encoding='UTF-8'?>  
2. <!DOCTYPE hibernate-configuration PUBLIC  
3.           "-//Hibernate/Hibernate Configuration DTD 5.3//EN"  
4.           "http://hibernate.sourceforge.net/hibernate-configuration-5.3.dtd">  
5.   
6. <hibernate-configuration>  
7.   
8.     <session-factory>  
9.         <property name="hbm2ddl.auto">update</property>  
10.         <property name="dialect">org.hibernate.dialect.Oracle9Dialect</property>  
11.         <property name="connection.url">jdbc:oracle:thin:@localhost:1521:xe</prop
erty>  
12.         <property name="connection.username">system</property>  
13.         <property name="connection.password">jtp</property>  
14.         <property name="connection.driver_class">oracle.jdbc.driver.OracleDriver</pr
operty>  
15.     <mapping resource="question.hbm.xml"/>  
16.     </session-factory>  
17.   
18. </hibernate-configuration>  

4) Create the class to store the data


In this class we are storing the data of the question class.

1. package com.javatpoint;    
2.     
3. import java.util.HashSet;    
4.     
5. import org.hibernate.*;  
6. import org.hibernate.boot.Metadata;  
7. import org.hibernate.boot.MetadataSources;  
8. import org.hibernate.boot.registry.StandardServiceRegistry;  
9. import org.hibernate.boot.registry.StandardServiceRegistryBuilder;   
10.     
11. public class StoreData {    
12.  public static void main(String[] args) {    
13.       
14.      StandardServiceRegistry ssr=new StandardServiceRegistryBuilder().configure("hi
bernate.cfg.xml").build();  
15.         Metadata meta=new MetadataSources(ssr).getMetadataBuilder().build();  
16.           
17.         SessionFactory factory=meta.getSessionFactoryBuilder().build();  
18.         Session session=factory.openSession();  
19.        
20.  Transaction t=session.beginTransaction();    
21.         
22.     
23.     HashSet<String> set1=new HashSet<String>();    
24.     set1.add("Java is a programming language");    
25.     set1.add("Java is a platform");    
26.         
27.     HashSet<String> set2=new HashSet<String>();    
28.     set2.add("Servlet is an Interface");    
29.     set2.add("Servlet is an API");    
30.         
31.     Question question1=new Question();    
32.     question1.setQname("What is Java?");    
33.     question1.setAnswers(set1);    
34.         
35.     Question question2=new Question();    
36.     question2.setQname("What is Servlet?");    
37.     question2.setAnswers(set2);    
38.         
39.     session.persist(question1);    
40.     session.persist(question2);    
41.         
42.     t.commit();    
43.     session.close();    
44.     System.out.println("success");    
45.  }    
46. }    

Output
 

How to fetch the data of Set


Here, we have used HQL to fetch all the records of Question class including answers. In
such case, it fetches the data from two tables that are functional dependent.

1. package com.javatpoint;    
2.     
3. import java.util.*;  
4.   
5. import javax.persistence.TypedQuery;  
6.   
7. import org.hibernate.*;  
8. import org.hibernate.boot.Metadata;  
9. import org.hibernate.boot.MetadataSources;  
10. import org.hibernate.boot.registry.StandardServiceRegistry;  
11. import org.hibernate.boot.registry.StandardServiceRegistryBuilder;  
12.     
13. public class FetchData {    
14. public static void main(String[] args) {    
15.         
16.      StandardServiceRegistry ssr=new StandardServiceRegistryBuilder().configure("hi
bernate.cfg.xml").build();  
17.         Metadata meta=new MetadataSources(ssr).getMetadataBuilder().build();  
18.           
19.         SessionFactory factory=meta.getSessionFactoryBuilder().build();  
20.         Session session=factory.openSession();  
21.        
22.  Transaction t=session.beginTransaction();    
23.         
24.     TypedQuery query=session.createQuery("from Question");    
25.     List<Question> list=query.getResultList();    
26.         
27.     Iterator<Question> itr=list.iterator();    
28.     while(itr.hasNext()){    
29.         Question q=itr.next();    
30.         System.out.println("Question Name: "+q.getQname());    
31.             
32.         //printing answers    
33.         Set<String> set=q.getAnswers();    
34.         Iterator<String> itr2=set.iterator();    
35.         while(itr2.hasNext()){    
36.             System.out.println(itr2.next());    
37.         }    
38.             
39.     }    
40.     session.close();    
41.     System.out.println("success");    
42.         
43. }    
44. }    

Output

Hibernate Mapping Map using xml file


1. Mapping Map in collection mapping
2. Example of Mapping Map in collection mapping

Hibernate allows you to map Map elements with the RDBMS. As we know, list and map are
index-based collections. In case of map, index column works as the key and element
column works as the value.

Example of Mapping Map in collection mapping using xml file


You need to create following pages for mapping map elements.

o Question.java
o question.hbm.xml
o hibernate.cfg.xml
o StoreTest.java
o FetchTest.java

Question.java

1. package com.javatpoint;  
2.   
3. import java.util.Map;  
4.   
5. public class Question {  
6. private int id;  
7. private String name,username;  
8. private Map<String,String> answers;  
9.   
10. public Question() {}  
11. public Question(String name, String username, Map<String, String> answers) {  
12.     super();  
13.     this.name = name;  
14.     this.username = username;  
15.     this.answers = answers;  
16. }  
17. public int getId() {  
18.     return id;  
19. }  
20. public void setId(int id) {  
21.     this.id = id;  
22. }  
23. public String getName() {  
24.     return name;  
25. }  
26. public void setName(String name) {  
27.     this.name = name;  
28. }  
29. public String getUsername() {  
30.     return username;  
31. }  
32. public void setUsername(String username) {  
33.     this.username = username;  
34. }  
35. public Map<String, String> getAnswers() {  
36.     return answers;  
37. }  
38. public void setAnswers(Map<String, String> answers) {  
39.     this.answers = answers;  
40. }  
41. }  

question.hbm.xml

1. <?xml version='1.0' encoding='UTF-8'?>  
2. <!DOCTYPE hibernate-mapping PUBLIC  
3.           "-//Hibernate/Hibernate Mapping DTD 5.3//EN"  
4.           "http://hibernate.sourceforge.net/hibernate-mapping-5.3.dtd">  
5.             
6. <hibernate-mapping>  
7.   
8. <class name="com.javatpoint.Question" table="question736">  
9. <id name="id">  
10. <generator class="native"></generator>  
11. </id>  
12. <property name="name"></property>  
13. <property name="username"></property>  
14.   
15. <map name="answers" table="answer736" cascade="all">  
16. <key column="questionid"></key>  
17. <index column="answer" type="string"></index>  
18. <element column="username" type="string"></element>  
19. </map>  
20. </class>  
21.   
22. </hibernate-mapping>                    
hibernate.cfg.xml

1. <?xml version='1.0' encoding='UTF-8'?>  
2. <!DOCTYPE hibernate-configuration PUBLIC  
3.           "-//Hibernate/Hibernate Configuration DTD 5.3//EN"  
4.           "http://hibernate.sourceforge.net/hibernate-configuration-5.3.dtd">  
5.   
6. <hibernate-configuration>  
7.   
8.     <session-factory>  
9.         <property name="hbm2ddl.auto">update</property>  
10.         <property name="dialect">org.hibernate.dialect.Oracle9Dialect</property>  
11.         <property name="connection.url">jdbc:oracle:thin:@localhost:1521:xe</prop
erty>  
12.         <property name="connection.username">system</property>  
13.         <property name="connection.password">jtp</property>  
14.         <property name="connection.driver_class">oracle.jdbc.driver.OracleDriver</pr
operty>  
15.       
16.     <mapping resource="question.hbm.xml"/>  
17.     </session-factory>  
18.   
19. </hibernate-configuration>  

StoreTest.java

1. package com.javatpoint;    
2.     
3. import java.util.HashMap;    
4. import org.hibernate.*;  
5. import org.hibernate.boot.Metadata;  
6. import org.hibernate.boot.MetadataSources;  
7. import org.hibernate.boot.registry.StandardServiceRegistry;  
8. import org.hibernate.boot.registry.StandardServiceRegistryBuilder;    
9.   
10.   
11. public class StoreTest {    
12. public static void main(String[] args) {    
13.    
14.     StandardServiceRegistry ssr=new StandardServiceRegistryBuilder().configure("hi
bernate.cfg.xml").build();  
15.     Metadata meta=new MetadataSources(ssr).getMetadataBuilder().build();  
16.       
17.     SessionFactory factory=meta.getSessionFactoryBuilder().build();  
18.     Session session=factory.openSession();  
19.    
20. Transaction t=session.beginTransaction();    
21.     
22. HashMap<String,String> map1=new HashMap<String,String>();    
23. map1.put("Java is a programming language","John Milton");    
24. map1.put("Java is a platform","Ashok Kumar");    
25.     
26. HashMap<String,String> map2=new HashMap<String,String>();    
27. map2.put("Servlet technology is a server side programming","John Milton");    
28. map2.put("Servlet is an Interface","Ashok Kumar");    
29. map2.put("Servlet is a package","Rahul Kumar");    
30.     
31. Question question1=new Question("What is Java?","Alok",map1);    
32. Question question2=new Question("What is Servlet?","Jai Dixit",map2);    
33.     
34. session.persist(question1);    
35. session.persist(question2);    
36.     
37. t.commit();    
38. session.close();    
39. System.out.println("successfully stored");    
40. }    
41. }    

Output

FetchTest.java

1. package com.javatpoint;    
2. import java.util.*;  
3.   
4. import javax.persistence.TypedQuery;  
5.   
6. import org.hibernate.*;  
7. import org.hibernate.boot.Metadata;  
8. import org.hibernate.boot.MetadataSources;  
9. import org.hibernate.boot.registry.StandardServiceRegistry;  
10. import org.hibernate.boot.registry.StandardServiceRegistryBuilder;  
11.    
12. public class FetchTest {    
13. public static void main(String[] args) {    
14.     StandardServiceRegistry ssr=new StandardServiceRegistryBuilder().configure("hi
bernate.cfg.xml").build();  
15.     Metadata meta=new MetadataSources(ssr).getMetadataBuilder().build();  
16.       
17.     SessionFactory factory=meta.getSessionFactoryBuilder().build();  
18.     Session session=factory.openSession();    
19.             
20.  TypedQuery query=session.createQuery("from Question ");    
21.  List<Question> list=query.getResultList();    
22.             
23.  Iterator<Question> iterator=list.iterator();    
24.  while(iterator.hasNext()){    
25.   Question question=iterator.next();    
26.   System.out.println("question id:"+question.getId());    
27.   System.out.println("question name:"+question.getName());    
28.   System.out.println("question posted by:"+question.getUsername());    
29.   System.out.println("answers.....");    
30.   Map<String,String> map=question.getAnswers();    
31.   Set<Map.Entry<String,String>> set=map.entrySet();    
32.                 
33.   Iterator<Map.Entry<String,String>> iteratoranswer=set.iterator();    
34.   while(iteratoranswer.hasNext()){    
35.    Map.Entry<String,String> entry=(Map.Entry<String,String>)iteratoranswer.next()
;    
36.    System.out.println("answer name:"+entry.getKey());    
37.    System.out.println("answer posted by:"+entry.getValue());    
38.   }    
39.  }    
40. session.close();    
41. }    
42. }    
Output

Hibernate One to Many Example using XML


1. List One to many
2. Example of mapping list in collection mapping by one to many association

If the persistent class has list object that contains the entity reference, we need to use one-
to-many association to map the list element.

Here, we are using the scenario of Forum where one question has multiple answers.
In such case, there can be many answers for a question and each answer may have its own
informations that is why we have used list in the persistent class (containing the reference
of Answer class) to represent a collection of answers.

Let's see the persistent class that has list objects (containing Answer class objects).

1. package com.javatpoint;  
2.   
3. import java.util.List;  
4.   
5. public class Question {  
6. private int id;  
7. private String qname;  
8. private List<Answer> answers;  
9. //getters and setters  
10.   
11. }  

The Answer class has its own informations such as id, answername, postedBy etc.

1. package com.javatpoint;  
2.   
3. public class Answer {  
4. private int id;  
5. private String answername;  
6. private String postedBy;  
7. //getters and setters  
8.   
9. }  
10. }  

The Question class has list object that have entity reference (i.e. Answer class object). In
such case, we need to use one-to-many of list to map this object. Let's see how we can
map it.

1. <list name="answers" cascade="all">  
2.           <key column="qid"></key>  
3.           <index column="type"></index>  
4.           <one-to-many class="com.javatpoint.Answer"/>  
5. </list>  

Full example of One to Many mapping in Hibernate by List


In this example, we are going to see full example of mapping list that contains entity
reference.

1) Create the Persistent class


This persistent class defines properties of the class including List.

Question.java
1. package com.javatpoint;  
2.   
3. import java.util.List;  
4.   
5. public class Question {  
6. private int id;  
7. private String qname;  
8. private List<Answer> answers;  
9.   
10. //getters and setters  
11.   
12. }  

Answer.java
1. package com.javatpoint;  
2.   
3. public class Answer {  
4. private int id;  
5. private String answername;  
6. private String postedBy;  
7. //getters and setters  
8.   
9. }  
10. }  

2) Create the Mapping file for the persistent class


Here, we have created the question.hbm.xml file for defining the list.

1. <?xml version='1.0' encoding='UTF-8'?>  
2. <!DOCTYPE hibernate-mapping PUBLIC  
3.           "-//Hibernate/Hibernate Mapping DTD 5.3//EN"  
4.           "http://hibernate.sourceforge.net/hibernate-mapping-5.3.dtd">  
5.   
6.           <hibernate-mapping>  
7.           <class name="com.javatpoint.Question" table="q501">  
8.           <id name="id">  
9.           <generator class="increment"></generator>  
10.           </id>  
11.           <property name="qname"></property>  
12.             
13.           <list name="answers" cascade="all">  
14.           <key column="qid"></key>  
15.           <index column="type"></index>  
16.           <one-to-many class="com.javatpoint.Answer"/>  
17.           </list>  
18.             
19.           </class>  
20.             
21.           <class name="com.javatpoint.Answer" table="ans501">  
22.           <id name="id">  
23.           <generator class="increment"></generator>  
24.           </id>  
25.           <property name="answername"></property>  
26.           <property name="postedBy"></property>  
27.           </class>  
28.             
29.           </hibernate-mapping>  

3) Create the configuration file


This file contains information about the database and mapping file.

1. <?xml version='1.0' encoding='UTF-8'?>  
2. <!DOCTYPE hibernate-configuration PUBLIC  
3.           "-//Hibernate/Hibernate Configuration DTD 5.3//EN"  
4.           "http://hibernate.sourceforge.net/hibernate-configuration-5.3.dtd">  
5.   
6. <!-- Generated by MyEclipse Hibernate Tools.                   -->  
7. <hibernate-configuration>  
8.   
9.     <session-factory>  
10.         <property name="hbm2ddl.auto">update</property>  
11.         <property name="dialect">org.hibernate.dialect.Oracle9Dialect</property>  
12.         <property name="connection.url">jdbc:oracle:thin:@localhost:1521:xe</prop
erty>  
13.         <property name="connection.username">system</property>  
14.         <property name="connection.password">jtp</property>  
15.         <property name="connection.driver_class">oracle.jdbc.driver.OracleDriver</pr
operty>  
16.     <mapping resource="question.hbm.xml"/>  
17.     </session-factory>  
18.   
19. </hibernate-configuration>  

4) Create the class to store the data


In this class we are storing the data of the question class.

1. package com.javatpoint;    
2.   
3. import java.util.ArrayList;    
4. import org.hibernate.Session;  
5. import org.hibernate.SessionFactory;  
6. import org.hibernate.Transaction;  
7. import org.hibernate.boot.Metadata;  
8. import org.hibernate.boot.MetadataSources;  
9. import org.hibernate.boot.registry.StandardServiceRegistry;  
10. import org.hibernate.boot.registry.StandardServiceRegistryBuilder;  
11. public class StoreData {    
12. public static void main(String[] args) {    
13.      
14.     StandardServiceRegistry ssr=new StandardServiceRegistryBuilder().configure("hi
bernate.cfg.xml").build();  
15.     Metadata meta=new MetadataSources(ssr).getMetadataBuilder().build();  
16.       
17.     SessionFactory factory=meta.getSessionFactoryBuilder().build();  
18.     Session session=factory.openSession();  
19.       
20.     Transaction t=session.beginTransaction();    
21.         
22.     Answer ans1=new Answer();    
23.     ans1.setAnswername("Java is a programming language");    
24.     ans1.setPostedBy("Ravi Malik");    
25.         
26.     Answer ans2=new Answer();    
27.     ans2.setAnswername("Java is a platform");    
28.     ans2.setPostedBy("Sudhir Kumar");    
29.         
30.     Answer ans3=new Answer();    
31.     ans3.setAnswername("Servlet is an Interface");    
32.     ans3.setPostedBy("Jai Kumar");    
33.         
34.     Answer ans4=new Answer();    
35.     ans4.setAnswername("Servlet is an API");    
36.     ans4.setPostedBy("Arun");    
37.         
38.     ArrayList<Answer> list1=new ArrayList<Answer>();    
39.     list1.add(ans1);    
40.     list1.add(ans2);    
41.         
42.     ArrayList<Answer> list2=new ArrayList<Answer>();    
43.     list2.add(ans3);    
44.     list2.add(ans4);    
45.         
46.     Question question1=new Question();    
47.     question1.setQname("What is Java?");    
48.     question1.setAnswers(list1);    
49.         
50.     Question question2=new Question();    
51.     question2.setQname("What is Servlet?");    
52.     question2.setAnswers(list2);    
53.         
54.     session.persist(question1);    
55.     session.persist(question2);    
56.         
57.     t.commit();    
58.     session.close();    
59.     System.out.println("success");    
60. }    
61. }    

OUTPUT
 

How to fetch the data of List


Here, we have used HQL to fetch all the records of Question class including answers. In
such case, it fetches the data from two tables that are functional dependent. Here, we are
direct printing the object of answer class, but we have overridden the toString() method in
the Answer class returning answername and poster name. So it prints the answer name and
postername rather than reference id.

FetchData.java
1. package com.javatpoint;    
2. import java.util.*;  
3. import javax.persistence.TypedQuery;  
4. import org.hibernate.*;  
5. import org.hibernate.boot.Metadata;  
6. import org.hibernate.boot.MetadataSources;  
7. import org.hibernate.boot.registry.StandardServiceRegistry;  
8. import org.hibernate.boot.registry.StandardServiceRegistryBuilder;  
9.     
10. public class FetchData {    
11. public static void main(String[] args) {    
12.         
13.     StandardServiceRegistry ssr=new StandardServiceRegistryBuilder().configure("hi
bernate.cfg.xml").build();  
14.     Metadata meta=new MetadataSources(ssr).getMetadataBuilder().build();  
15.       
16.     SessionFactory factory=meta.getSessionFactoryBuilder().build();  
17.     Session session=factory.openSession();  
18.         
19.     TypedQuery query=session.createQuery("from Question");    
20.     List<Question> list=query.getResultList();    
21.         
22.     Iterator<Question> itr=list.iterator();    
23.     while(itr.hasNext()){    
24.         Question q=itr.next();    
25.         System.out.println("Question Name: "+q.getQname());    
26.             
27.         //printing answers    
28.         List<Answer> list2=q.getAnswers();    
29.         Iterator<Answer> itr2=list2.iterator();    
30.        while(itr2.hasNext())  
31.        {  
32.         Answer a=itr2.next();  
33.             System.out.println(a.getAnswername()+":"+a.getPostedBy());  
34.         }    
35.     }  
36.     session.close();    
37.     System.out.println("success");    
38.     }      
39. }    

OUTPUT

ibernate One to Many Example using


Annotation
In this section, we will perform one-to-many association to map the list object of persistent
class using annotation.

Here, we are using the scenario of Forum where one question has multiple answers.
 

In such case, there can be many answers for a question and each answer may have its own
information that is why we have used list in the persistent class (containing the reference of
Answer class) to represent a collection of answers.

Example of One to Many mapping using annotation


1) Create the Persistent class
This persistent class defines properties of the class including List.

Question.java

1. package com.javatpoint;    
2. import javax.persistence.*;  
3. import java.util.List;    
4.   
5. @Entity  
6. @Table(name="q5991")  
7. public class Question {    
8.   
9. @Id   
10. @GeneratedValue(strategy=GenerationType.TABLE)  
11. private int id;    
12. private String qname;    
13.   
14. @OneToMany(cascade = CascadeType.ALL)  
15. @JoinColumn(name="qid")  
16. @OrderColumn(name="type")  
17. private List<Answer> answers;  
18. public int getId() {  
19.     return id;  
20. }  
21. public void setId(int id) {  
22.     this.id = id;  
23. }  
24. public String getQname() {  
25.     return qname;  
26. }  
27. public void setQname(String qname) {  
28.     this.qname = qname;  
29. }  
30. public List<Answer> getAnswers() {  
31.     return answers;  
32. }  
33. public void setAnswers(List<Answer> answers) {  
34.     this.answers = answers;  
35. }      
36. }  

Answer.java

1. package com.javatpoint;    
2.       
3.     import javax.persistence.*;  
4.   
5.     @Entity  
6.     @Table(name="ans5991")  
7.     public class Answer {   
8.     @Id  
9.     @GeneratedValue(strategy=GenerationType.TABLE)  
10.       
11.     private int id;    
12.     private String answername;    
13.     private String postedBy;  
14.     public int getId() {  
15.         return id;  
16.     }  
17.     public void setId(int id) {  
18.         this.id = id;  
19.     }  
20.     public String getAnswername() {  
21.         return answername;  
22.     }  
23.     public void setAnswername(String answername) {  
24.         this.answername = answername;  
25.     }  
26.     public String getPostedBy() {  
27.         return postedBy;  
28.     }  
29.     public void setPostedBy(String postedBy) {  
30.         this.postedBy = postedBy;  
31.     }      
32.     }    

2) Add project information and configuration in pom.xml file.


Open pom.xml file and click source. Now, add the below dependencies between
<dependencies> .... </dependencies> tag.

1. <dependency>  
2.     <groupId>org.hibernate</groupId>  
3.     <artifactId>hibernate-core</artifactId>  
4.     <version>5.3.1.Final</version>  
5. </dependency>  
6.       
7. <dependency>  
8.     <groupId>com.oracle</groupId>  
9.     <artifactId>ojdbc14</artifactId>  
10.     <version>10.2.0.4.0</version>  
11. </dependency>  

3) Create the configuration file


This file contains information about the database and mapping file.

1. <?xml version='1.0' encoding='UTF-8'?>    
2. <!DOCTYPE hibernate-configuration PUBLIC    
3.           "-//Hibernate/Hibernate Configuration DTD 5.3//EN"    
4.           "http://hibernate.sourceforge.net/hibernate-configuration-5.3.dtd">    
5.     
6. <hibernate-configuration>    
7.     
8.     <session-factory>    
9.         <property name="hbm2ddl.auto">update</property>    
10.         <property name="dialect">org.hibernate.dialect.Oracle9Dialect</property>    
11.         <property name="connection.url">jdbc:oracle:thin:@localhost:1521:xe</prop
erty>    
12.         <property name="connection.username">system</property>    
13.         <property name="connection.password">jtp</property>    
14.         <property name="connection.driver_class">oracle.jdbc.driver.OracleDriver</pr
operty>    
15.      <mapping class="com.javatpoint.Question"/>   
16.     </session-factory>    
17.     
18. </hibernate-configuration>    

4) Create the class to store the data


In this class we are storing the data of the question class.

1. package com.javatpoint;    
2.   
3. import java.util.ArrayList;    
4.   
5. import org.hibernate.Session;  
6. import org.hibernate.SessionFactory;  
7. import org.hibernate.Transaction;  
8. import org.hibernate.boot.Metadata;  
9. import org.hibernate.boot.MetadataSources;  
10. import org.hibernate.boot.registry.StandardServiceRegistry;  
11. import org.hibernate.boot.registry.StandardServiceRegistryBuilder;  
12. public class StoreData {    
13. public static void main(String[] args) {    
14.      
15.     StandardServiceRegistry ssr=new StandardServiceRegistryBuilder().configure("hi
bernate.cfg.xml").build();  
16.     Metadata meta=new MetadataSources(ssr).getMetadataBuilder().build();  
17.       
18.     SessionFactory factory=meta.getSessionFactoryBuilder().build();  
19.     Session session=factory.openSession();  
20.       
21.     Transaction t=session.beginTransaction();    
22.         
23.     Answer ans1=new Answer();    
24.     ans1.setAnswername("Java is a programming language");    
25.     ans1.setPostedBy("Ravi Malik");    
26.         
27.     Answer ans2=new Answer();    
28.     ans2.setAnswername("Java is a platform");    
29.     ans2.setPostedBy("Sudhir Kumar");    
30.         
31.     Answer ans3=new Answer();    
32.     ans3.setAnswername("Servlet is an Interface");    
33.     ans3.setPostedBy("Jai Kumar");    
34.         
35.     Answer ans4=new Answer();    
36.     ans4.setAnswername("Servlet is an API");    
37.     ans4.setPostedBy("Arun");    
38.         
39.     ArrayList<Answer> list1=new ArrayList<Answer>();    
40.     list1.add(ans1);    
41.     list1.add(ans2);    
42.         
43.     ArrayList<Answer> list2=new ArrayList<Answer>();    
44.     list2.add(ans3);    
45.     list2.add(ans4);    
46.         
47.     Question question1=new Question();    
48.     question1.setQname("What is Java?");    
49.     question1.setAnswers(list1);    
50.         
51.     Question question2=new Question();    
52.     question2.setQname("What is Servlet?");    
53.     question2.setAnswers(list2);    
54.         
55.     session.persist(question1);    
56.     session.persist(question2);    
57.         
58.     t.commit();    
59.     session.close();    
60.     System.out.println("success");    
61. }    
62. }   
Note - Using these annotations in a similar way, we can also perform one-to-many association for
set, map and bag objects.

Output

How to fetch the data of List


Here, we have used HQL to fetch all the records of Question class including answers. In
such case, it fetches the data from two tables that are functional dependent.

1. package com.javatpoint;    
2. import java.util.*;  
3. import javax.persistence.TypedQuery;  
4. import org.hibernate.*;  
5. import org.hibernate.boot.Metadata;  
6. import org.hibernate.boot.MetadataSources;  
7. import org.hibernate.boot.registry.StandardServiceRegistry;  
8. import org.hibernate.boot.registry.StandardServiceRegistryBuilder;   
9.     
10. public class FetchData {    
11. public static void main(String[] args) {    
12.         
13.     StandardServiceRegistry ssr=new StandardServiceRegistryBuilder().configure("hi
bernate.cfg.xml").build();  
14.     Metadata meta=new MetadataSources(ssr).getMetadataBuilder().build();  
15.       
16.     SessionFactory factory=meta.getSessionFactoryBuilder().build();  
17.     Session session=factory.openSession();  
18.         
19.     TypedQuery query=session.createQuery("from Question");    
20.     List<Question> list=query.getResultList();    
21.         
22.     Iterator<Question> itr=list.iterator();    
23.     while(itr.hasNext()){    
24.         Question q=itr.next();    
25.         System.out.println("Question Name: "+q.getQname());    
26.             
27.         //printing answers    
28.         List<Answer> list2=q.getAnswers();    
29.         Iterator<Answer> itr2=list2.iterator();    
30.        while(itr2.hasNext())  
31.        {  
32.         Answer a=itr2.next();  
33.             System.out.println(a.getAnswername()+":"+a.getPostedBy());  
34.         }    
35.     }  
36.     session.close();    
37.     System.out.println("success");    
38. }    
39. }    

Output

Hibernate Many to Many Example using XML


We can map many to many relation either using list, set, bag, map, etc. Here, we are going
to use list for many-to-many mapping. In such case, three tables will be created.

Example of Many to Many Mapping


In this example, we will generate a many to many relation between questions and answers
using list.

1) Create the Persistent class


There are two persistent classes Question.java and Answer.java. Question class contains
Answer class reference and vice versa.

Question.java

1. package com.javatpoint;    
2.     
3. import java.util.List;    
4.     
5. public class Question {    
6. private int id;    
7. private String qname;    
8. private List<Answer> answers;  
9.   
10. public int getId() {  
11.     return id;  
12. }  
13. public void setId(int id) {  
14.     this.id = id;  
15. }  
16. public String getQname() {  
17.     return qname;  
18. }  
19. public void setQname(String qname) {  
20.     this.qname = qname;  
21. }  
22. public List<Answer> getAnswers() {  
23.     return answers;  
24. }  
25. public void setAnswers(List<Answer> answers) {  
26.     this.answers = answers;  
27. }      
28. }  

Answer.java

1. package com.javatpoint;  
2.   
3. import java.util.*;  
4.   
5. public class Answer {    
6. private int id;    
7. private String answername;    
8. private String postedBy;    
9. private List<Question> questions;  
10. public int getId() {  
11.     return id;  
12. }  
13. public void setId(int id) {  
14.     this.id = id;  
15. }  
16. public String getAnswername() {  
17.     return answername;  
18. }  
19. public void setAnswername(String answername) {  
20.     this.answername = answername;  
21. }  
22. public String getPostedBy() {  
23.     return postedBy;  
24. }  
25. public void setPostedBy(String postedBy) {  
26.     this.postedBy = postedBy;  
27. }  
28. public List<Question> getQuestions() {  
29.     return questions;  
30. }  
31. public void setQuestions(List<Question> questions) {  
32.     this.questions = questions;  
33. }    
34. }  

2) Create the Mapping file for the persistent class


Here, we have created the question.hbm.xml and answer.hbm.xml file for defining the list.

question.hbm.xml

1. <?xml version='1.0' encoding='UTF-8'?>    
2. <!DOCTYPE hibernate-mapping PUBLIC    
3.           "-//Hibernate/Hibernate Mapping DTD 5.3//EN"    
4.           "http://hibernate.sourceforge.net/hibernate-mapping-5.3.dtd">    
5.               
6. <hibernate-mapping>    
7.   
8.   <class name="com.javatpoint.Question" table="ques1911">  
9.         <id name="id" type="int">  
10.             <column name="q_id" />  
11.             <generator class="increment" />  
12.         </id>  
13.         <property name="qname" />  
14.   
15.         <list name="answers" table="ques_ans1911" fetch="select" cascade="all">  
16.             <key column="q_id" />  
17.                <index column="type"></index>   
18.             <many-to-many class="com.javatpoint.Answer" column="ans_id" />  
19.         </list>  
20.     </class>   
21. </hibernate-mapping>         

answer.hbm.xml

1. <?xml version='1.0' encoding='UTF-8'?>    
2. <!DOCTYPE hibernate-mapping PUBLIC    
3.           "-//Hibernate/Hibernate Mapping DTD 5.3//EN"    
4.           "http://hibernate.sourceforge.net/hibernate-mapping-5.3.dtd">    
5.               
6. <hibernate-mapping>    
7. <class name="com.javatpoint.Answer" table="ans1911">  
8.         <id name="id" type="int">  
9.             <column name="ans_id" />  
10.             <generator class="increment" />  
11.         </id>  
12.         <property name="answername"  />  
13.         <property name="postedBy" />  
14.     </class>  
15. </hibernate-mapping>  

3) Create the configuration file


This file contains information about the database and mapping file.

hibernate.cfg.xml

1. <?xml version='1.0' encoding='UTF-8'?>    
2. <!DOCTYPE hibernate-configuration PUBLIC    
3.           "-//Hibernate/Hibernate Configuration DTD 5.3//EN"    
4.           "http://hibernate.sourceforge.net/hibernate-configuration-5.3.dtd">    
5.     
6. <hibernate-configuration>    
7.     
8.     <session-factory>    
9.         <property name="hbm2ddl.auto">create</property>    
10.         <property name="dialect">org.hibernate.dialect.Oracle9Dialect</property>    
11.         <property name="connection.url">jdbc:oracle:thin:@localhost:1521:xe</prop
erty>    
12.         <property name="connection.username">system</property>    
13.         <property name="connection.password">jtp</property>    
14.         <property name="connection.driver_class">oracle.jdbc.driver.OracleDriver</pr
operty>    
15.     <mapping resource="question.hbm.xml"/>    
16.     <mapping resource="answer.hbm.xml"/>  
17.     </session-factory>    
18.     
19. </hibernate-configuration>    

4) Create the class to store the data


StoreData.java

1. package com.javatpoint;    
2. import java.util.ArrayList;    
3. import org.hibernate.*;  
4. import org.hibernate.boot.Metadata;  
5. import org.hibernate.boot.MetadataSources;  
6. import org.hibernate.boot.registry.StandardServiceRegistry;  
7. import org.hibernate.boot.registry.StandardServiceRegistryBuilder;  
8.      
9. public class StoreData {    
10. public static void main(String[] args) {    
11.      
12.     StandardServiceRegistry ssr=new StandardServiceRegistryBuilder().configure("hi
bernate.cfg.xml").build();    
13.     Metadata meta=new MetadataSources(ssr).getMetadataBuilder().build();    
14.     SessionFactory factory=meta.getSessionFactoryBuilder().build();    
15.     Session session=factory.openSession();    
16.     Transaction t=session.beginTransaction();      
17.           
18.     Answer ans1=new Answer();  
19.     ans1.setAnswername("Java is a programming language");  
20.     ans1.setPostedBy("Ravi Malik");  
21.       
22.     Answer ans2=new Answer();  
23.     ans2.setAnswername("Java is a platform");  
24.     ans2.setPostedBy("Sudhir Kumar");  
25.      
26.     Question q1=new Question();  
27.     q1.setQname("What is Java?");  
28.     ArrayList<Answer> l1=new ArrayList<Answer>();  
29.     l1.add(ans1);  
30.     l1.add(ans2);  
31.     q1.setAnswers(l1);  
32.       
33.     Answer ans3=new Answer();    
34.     ans3.setAnswername("Servlet is an Interface");    
35.     ans3.setPostedBy("Jai Kumar");    
36.             
37.     Answer ans4=new Answer();    
38.     ans4.setAnswername("Servlet is an API");    
39.     ans4.setPostedBy("Arun");    
40.       
41.     Question q2=new Question();  
42.     q2.setQname("What is Servlet?");  
43.     ArrayList<Answer> l2=new ArrayList<Answer>();  
44.     l2.add(ans3);  
45.     l2.add(ans4);  
46.     q2.setAnswers(l2);  
47.     session.persist(q1);    
48.     session.persist(q2);    
49.         
50.     t.commit();    
51.     session.close();    
52.     System.out.println("success");        
53. }    
54. }    

Output
 

Hibernate Many to Many Example using


Annotation
In the previous section, we have performed many to many mapping using XML file. Here,
we are going to perform this task using annotation.

We can map many to many relation either using list, set, bag, map etc. Here, we are going
to use list for many-to-many mapping. In such case, three tables will be created.

Example of Many to Many Mapping


In this example, we will generate a many to many relation between questions and answers
by list.

1) Create the Persistent class


Question.java

1. package com.javatpoint;    
2.     
3. import java.util.List;  
4. import javax.persistence.*;    
5.     
6. @Entity  
7. @Table(name="ques1123")  
8. public class Question {    
9.     @Id  
10.     @GeneratedValue(strategy=GenerationType.AUTO)  
11. private int id;    
12. private String qname;   
13.   
14. @ManyToMany(targetEntity = Answer.class, cascade = { CascadeType.ALL })  
15. @JoinTable(name = "q_ans1123",   
16.             joinColumns = { @JoinColumn(name = "q_id") },   
17.             inverseJoinColumns = { @JoinColumn(name = "ans_id") })  
18. private List<Answer> answers;  
19.   
20. public int getId() {  
21.     return id;  
22. }  
23. public void setId(int id) {  
24.     this.id = id;  
25. }  
26. public String getQname() {  
27.     return qname;  
28. }  
29. public void setQname(String qname) {  
30.     this.qname = qname;  
31. }  
32. public List<Answer> getAnswers() {  
33.     return answers;  
34. }  
35. public void setAnswers(List<Answer> answers) {  
36.     this.answers = answers;  
37. }      
38. }  

Answer.java

1. package com.javatpoint;  
2.   
3. import javax.persistence.*;  
4.   
5. @Entity  
6. @Table(name="ans1123")  
7. public class Answer {   
8.       
9.     @Id  
10.     @GeneratedValue(strategy=GenerationType.AUTO)  
11. private int id;    
12. private String answername;    
13. private String postedBy;    
14. public int getId() {  
15.     return id;  
16. }  
17. public void setId(int id) {  
18.     this.id = id;  
19. }  
20. public String getAnswername() {  
21.     return answername;  
22. }  
23. public void setAnswername(String answername) {  
24.     this.answername = answername;  
25. }  
26. public String getPostedBy() {  
27.     return postedBy;  
28. }  
29. public void setPostedBy(String postedBy) {  
30.     this.postedBy = postedBy;  
31. }  
32.   
33. }    

2) Add project information and configuration in pom.xml file.


Open pom.xml file and click source. Now, add the below dependencies between
<dependencies>....</dependencies> tag.

1. <dependency>    
2.     <groupId>org.hibernate</groupId>    
3.     <artifactId>hibernate-core</artifactId>    
4.     <version>5.3.1.Final</version>    
5. </dependency>    

1. <dependency>    
2.     <groupId>com.oracle</groupId>    
3.     <artifactId>ojdbc14</artifactId>    
4.     <version>10.2.0.4.0</version>    
5. </dependency>    

3) Create the configuration file


This file contains information about the database and mapping file.

1. <?xml version='1.0' encoding='UTF-8'?>    
2. <!DOCTYPE hibernate-configuration PUBLIC    
3.           "-//Hibernate/Hibernate Configuration DTD 5.3//EN"    
4.           "http://hibernate.sourceforge.net/hibernate-configuration-5.3.dtd">    
5.     
6. <hibernate-configuration>    
7.     
8.     <session-factory>    
9.         <property name="hbm2ddl.auto">create</property>    
10.         <property name="dialect">org.hibernate.dialect.Oracle9Dialect</property>    
11.         <property name="connection.url">jdbc:oracle:thin:@localhost:1521:xe</prop
erty>    
12.         <property name="connection.username">system</property>    
13.         <property name="connection.password">jtp</property>    
14.         <property name="connection.driver_class">oracle.jdbc.driver.OracleDriver</pr
operty>    
15.     <mapping class="com.javatpoint.Question"/>    
16.     <mapping class="com.javatpoint.Answer"/>  
17.     </session-factory>    
18.     
19. </hibernate-configuration>  

4) Create the class to store the data


StoreData.java

1. package com.javatpoint;    
2. import java.util.ArrayList;    
3. import org.hibernate.*;  
4. import org.hibernate.boot.Metadata;  
5. import org.hibernate.boot.MetadataSources;  
6. import org.hibernate.boot.registry.StandardServiceRegistry;  
7. import org.hibernate.boot.registry.StandardServiceRegistryBuilder;  
8.      
9. public class StoreData {    
10. public static void main(String[] args) {    
11.      
12.     StandardServiceRegistry ssr=new StandardServiceRegistryBuilder().configure("hi
bernate.cfg.xml").build();    
13.     Metadata meta=new MetadataSources(ssr).getMetadataBuilder().build();    
14.     SessionFactory factory=meta.getSessionFactoryBuilder().build();    
15.     Session session=factory.openSession();    
16.     Transaction t=session.beginTransaction();      
17.           
18.     Answer an1=new Answer();  
19.     an1.setAnswername("Java is a programming language");  
20.     an1.setPostedBy("Ravi Malik");  
21.       
22.     Answer an2=new Answer();  
23.     an2.setAnswername("Java is a platform");  
24.     an2.setPostedBy("Sudhir Kumar");  
25.      
26.     Question q1=new Question();  
27.     q1.setQname("What is Java?");  
28.     ArrayList<Answer> l1=new ArrayList<Answer>();  
29.     l1.add(an1);  
30.     l1.add(an2);  
31.     q1.setAnswers(l1);  
32.       
33.       
34.       Answer ans3=new Answer();    
35.         ans3.setAnswername("Servlet is an Interface");    
36.         ans3.setPostedBy("Jai Kumar");    
37.             
38.         Answer ans4=new Answer();    
39.         ans4.setAnswername("Servlet is an API");    
40.         ans4.setPostedBy("Arun");    
41.       
42.     Question q2=new Question();  
43.     q2.setQname("What is Servlet?");  
44.     ArrayList<Answer> l2=new ArrayList<Answer>();  
45.     l2.add(ans3);  
46.     l2.add(ans4);  
47.     q2.setAnswers(l2);  
48.       
49.     session.persist(q1);    
50.     session.persist(q2);    
51.         
52.     t.commit();    
53.     session.close();    
54.     System.out.println("success");    
55.       
56.        
57. }    
58. }   

Output

Hibernate One to One Example using XML


1. Example of One to one mapping in hibernate
1. Persistent classes for one to one mapping
2. Mapping files for the persistent classes
3. Configuration file
4. User classes to store and fetch the data

There are two ways to perform one to one mapping in hibernate:

o By many-to-one element (using unique="true" attribute)


o By one-to-one element

Here, we are going to perform one to one mapping by one-to-one element. In such case, no
foreign key is created in the primary table.

In this example, one employee can have one address and one address belongs to one
employee only. Here, we are using bidirectional association. Let's look at the persistent
classes.

1) Persistent classes for one to one mapping


There are two persistent classes Employee.java and Address.java. Employee class contains
Address class reference and vice versa.

Employee.java
1. package com.javatpoint;  
2.   
3. public class Employee {  
4. private int employeeId;  
5. private String name,email;  
6. private Address address;  
7. //setters and getters  
8. }  

Address.java
1. package com.javatpoint;  
2.   
3. public class Address {  
4. private int addressId;  
5. private String addressLine1,city,state,country;  
6. private int pincode;  
7. private Employee employee;  
8. //setters and getters  
9. }  

2) Mapping files for the persistent classes


The two mapping files are employee.hbm.xml and address.hbm.xml.

employee.hbm.xml

In this mapping file we are using one-to-one element in both the mapping files to make
the one to one mapping.

1. <?xml version='1.0' encoding='UTF-8'?>  
2. <!DOCTYPE hibernate-mapping PUBLIC  
3.           "-//Hibernate/Hibernate Mapping DTD 5.3//EN"  
4.           "http://hibernate.sourceforge.net/hibernate-mapping-5.3.dtd">  
5.   
6.            <hibernate-mapping>  
7.           <class name="com.javatpoint.Employee" table="emp212">  
8.           <id name="employeeId">  
9.           <generator class="increment"></generator>  
10.           </id>  
11.           <property name="name"></property>  
12.           <property name="email"></property>  
13.             
14.           <one-to-one name="address" cascade="all"></one-to-one>  
15.           </class>  
16.             
17.           </hibernate-mapping>  
address.hbm.xml

This is the simple mapping file for the Address class. But the important thing is generator
class. Here, we are using foreign generator class that depends on the Employee class
primary key.

1. <?xml version='1.0' encoding='UTF-8'?>  
2. <!DOCTYPE hibernate-mapping PUBLIC  
3.           "-//Hibernate/Hibernate Mapping DTD 5.3//EN"  
4.           "http://hibernate.sourceforge.net/hibernate-mapping-5.3.dtd">  
5.   
6.            <hibernate-mapping>  
7.           <class name="com.javatpoint.Address" table="address212">  
8.           <id name="addressId">  
9.           <generator class="foreign">  
10.           <param name="property">employee</param>  
11.           </generator>  
12.           </id>  
13.           <property name="addressLine1"></property>  
14.           <property name="city"></property>  
15.           <property name="state"></property>  
16.           <property name="country"></property>  
17.           <property name="pincode"></property>  
18.             
19.           <one-to-one name="employee"></one-to-one>  
20.           </class>  
21.             
22.           </hibernate-mapping>  

3) Configuration file
This file contains information about the database and mapping file.

hibernate.cfg.xml
1. <?xml version='1.0' encoding='UTF-8'?>  
2. <!DOCTYPE hibernate-configuration PUBLIC  
3.           "-//Hibernate/Hibernate Configuration DTD 5.3//EN"  
4.           "http://hibernate.sourceforge.net/hibernate-configuration-5.3.dtd">  
5.   
6. <hibernate-configuration>  
7.   
8.     <session-factory>  
9.         <property name="hbm2ddl.auto">update</property>  
10.         <property name="dialect">org.hibernate.dialect.Oracle9Dialect</property>  
11.         <property name="connection.url">jdbc:oracle:thin:@localhost:1521:xe</prop
erty>  
12.         <property name="connection.username">system</property>  
13.         <property name="connection.password">jtp</property>  
14.         <property name="connection.driver_class">oracle.jdbc.driver.OracleDriver</pr
operty>  
15.     <mapping resource="employee.hbm.xml"/>  
16.     <mapping resource="address.hbm.xml"/>  
17.     </session-factory>  
18.   
19. </hibernate-configuration>  

4) User classes to store and fetch the data


Store.java
1. package com.javatpoint;    
2.     
3. import org.hibernate.*;  
4. import org.hibernate.boot.Metadata;  
5. import org.hibernate.boot.MetadataSources;  
6. import org.hibernate.boot.registry.StandardServiceRegistry;  
7. import org.hibernate.boot.registry.StandardServiceRegistryBuilder;    
8.     
9. public class Store {    
10. public static void main(String[] args) {    
11.       
12.     StandardServiceRegistry ssr=new StandardServiceRegistryBuilder().configure("hi
bernate.cfg.xml").build();  
13.     Metadata meta=new MetadataSources(ssr).getMetadataBuilder().build();  
14.       
15.     SessionFactory factory=meta.getSessionFactoryBuilder().build();  
16.     Session session=factory.openSession();  
17.       
18.     Transaction t=session.beginTransaction();   
19.       
20.     Employee e1=new Employee();    
21.     e1.setName("Ravi Malik");    
22.     e1.setEmail("[email protected]");    
23.         
24.     Address address1=new Address();    
25.     address1.setAddressLine1("G-21,Lohia nagar");    
26.     address1.setCity("Ghaziabad");    
27.     address1.setState("UP");    
28.     address1.setCountry("India");    
29.     address1.setPincode(201301);    
30.         
31.     e1.setAddress(address1);    
32.     address1.setEmployee(e1);    
33.         
34.     session.persist(e1);    
35.     t.commit();    
36.         
37.     session.close();    
38.     System.out.println("success");    
39. }    
40. }    

Output

Fetch.java
1. package com.javatpoint;    
2.   
3. import java.util.*;  
4. import javax.persistence.TypedQuery;  
5. import org.hibernate.Session;    
6. import org.hibernate.SessionFactory;  
7. import org.hibernate.boot.Metadata;  
8. import org.hibernate.boot.MetadataSources;  
9. import org.hibernate.boot.registry.StandardServiceRegistry;  
10. import org.hibernate.boot.registry.StandardServiceRegistryBuilder;   
11.     
12. public class Fetch {    
13. public static void main(String[] args) {    
14.     StandardServiceRegistry ssr=new StandardServiceRegistryBuilder().configure("hi
bernate.cfg.xml").build();  
15.     Metadata meta=new MetadataSources(ssr).getMetadataBuilder().build();  
16.       
17.     SessionFactory factory=meta.getSessionFactoryBuilder().build();  
18.     Session session=factory.openSession();  
19.         
20.     TypedQuery query=session.createQuery("from Employee e");    
21.     List<Employee> list=query.getResultList();    
22.         
23.     Iterator<Employee> itr=list.iterator();    
24.     while(itr.hasNext()){    
25.      Employee emp=itr.next();    
26.      System.out.println(emp.getEmployeeId()+" "+emp.getName()+" 
"+emp.getEmail());    
27.      Address address=emp.getAddress();    
28.      System.out.println(address.getAddressLine1()+" "+address.getCity()+" "+    
29.         address.getState()+" "+address.getCountry()+" "+address.getPincode());    
30.     }    
31.     
32.     session.close();    
33.     System.out.println("success");    
34. }    
35. }    

Output

ibernate One to One Example using Annotation


Here, we are going to perform one to one mapping by one-to-one element using annotation.
In such case, no foreign key is created in the primary table.

In this example, one employee can have one address and one address belongs to one
employee only. Here, we are using bidirectional association. Let's look at the persistent
classes.

1) Persistent classes for one to one mapping


There are two persistent classes Employee.java and Address.java. Employee class contains
Address class reference and vice versa.

Employee.java

1. package com.javatpoint;  
2. import javax.persistence.*;  
3.   
4. @Entity  
5. @Table(name="emp220")  
6. public class Employee {    
7.       
8.     @Id  
9.     @GeneratedValue(strategy=GenerationType.AUTO)  
10.     @PrimaryKeyJoinColumn  
11. private int employeeId;    
12. private String name,email;    
13. @OneToOne(targetEntity=Address.class,cascade=CascadeType.ALL)  
14. private Address address;  
15. public int getEmployeeId() {  
16.     return employeeId;  
17. }  
18. public void setEmployeeId(int employeeId) {  
19.     this.employeeId = employeeId;  
20. }  
21. public String getName() {  
22.     return name;  
23. }  
24. public void setName(String name) {  
25.     this.name = name;  
26. }  
27. public String getEmail() {  
28.     return email;  
29. }  
30. public void setEmail(String email) {  
31.     this.email = email;  
32. }  
33. public Address getAddress() {  
34.     return address;  
35. }  
36. public void setAddress(Address address) {  
37.     this.address = address;  
38. }    
39.   
40. }    

Address.java

1. package com.javatpoint;  
2. import javax.persistence.*;  
3.   
4. @Entity  
5. @Table(name="address220")  
6. public class Address {    
7.       
8.     @Id  
9.     @GeneratedValue(strategy=GenerationType.AUTO)  
10. private int addressId;    
11. private String addressLine1,city,state,country;    
12. private int pincode;    
13.   
14. @OneToOne(targetEntity=Employee.class)  
15. private Employee employee;  
16. public int getAddressId() {  
17.     return addressId;  
18. }  
19. public void setAddressId(int addressId) {  
20.     this.addressId = addressId;  
21. }  
22. public String getAddressLine1() {  
23.     return addressLine1;  
24. }  
25. public void setAddressLine1(String addressLine1) {  
26.     this.addressLine1 = addressLine1;  
27. }  
28. public String getCity() {  
29.     return city;  
30. }  
31. public void setCity(String city) {  
32.     this.city = city;  
33. }  
34. public String getState() {  
35.     return state;  
36. }  
37. public void setState(String state) {  
38.     this.state = state;  
39. }  
40. public String getCountry() {  
41.     return country;  
42. }  
43. public void setCountry(String country) {  
44.     this.country = country;  
45. }  
46. public int getPincode() {  
47.     return pincode;  
48. }  
49. public void setPincode(int pincode) {  
50.     this.pincode = pincode;  
51. }  
52. public Employee getEmployee() {  
53.     return employee;  
54. }  
55. public void setEmployee(Employee employee) {  
56.     this.employee = employee;  
57. }    
58. }  

2) Add project information and configuration in pom.xml file.


Open pom.xml file and click source. Now, add the below dependencies between
<dependencies>....</dependencies> tag. These dependencies are used to add the jar files
in Maven project.

1. <dependency>    
2.     <groupId>org.hibernate</groupId>    
3.     <artifactId>hibernate-core</artifactId>    
4.     <version>5.3.1.Final</version>    
5. </dependency>    

1. <dependency>    
2.     <groupId>com.oracle</groupId>    
3.     <artifactId>ojdbc14</artifactId>    
4.     <version>10.2.0.4.0</version>    
5. </dependency>    

3) Configuration file
This file contains information about the database and mapping file.

hibernate.cfg.xml

1. <?xml version='1.0' encoding='UTF-8'?>    
2. <!DOCTYPE hibernate-configuration PUBLIC    
3.           "-//Hibernate/Hibernate Configuration DTD 5.3//EN"    
4.           "http://hibernate.sourceforge.net/hibernate-configuration-5.3.dtd">    
5.      
6. <hibernate-configuration>    
7.     
8.     <session-factory>    
9.         <property name="hbm2ddl.auto">update</property>    
10.         <property name="dialect">org.hibernate.dialect.Oracle9Dialect</property>    
11.         <property name="connection.url">jdbc:oracle:thin:@localhost:1521:xe</prop
erty>    
12.         <property name="connection.username">system</property>    
13.         <property name="connection.password">jtp</property>    
14.         <property name="connection.driver_class">oracle.jdbc.driver.OracleDriver</pr
operty>    
15.     <mapping class="com.javatpoint.Address"/>    
16.     <mapping class="com.javatpoint.Employee"/>    
17.     </session-factory>    
18.     
19. </hibernate-configuration>    

4) User classes to store and fetch the data


Store.java

1. package com.javatpoint;    
2.     
3. import org.hibernate.*;  
4. import org.hibernate.boot.Metadata;  
5. import org.hibernate.boot.MetadataSources;  
6. import org.hibernate.boot.registry.StandardServiceRegistry;  
7. import org.hibernate.boot.registry.StandardServiceRegistryBuilder;    
8.     
9. public class Store {    
10. public static void main(String[] args) {    
11.       
12.     StandardServiceRegistry ssr=new StandardServiceRegistryBuilder().configure("hi
bernate.cfg.xml").build();  
13.     Metadata meta=new MetadataSources(ssr).getMetadataBuilder().build();  
14.       
15.     SessionFactory factory=meta.getSessionFactoryBuilder().build();  
16.     Session session=factory.openSession();  
17.       
18.     Transaction t=session.beginTransaction();   
19.       
20.     Employee e1=new Employee();    
21.     e1.setName("Ravi Malik");    
22.     e1.setEmail("[email protected]");    
23.         
24.     Address address1=new Address();    
25.     address1.setAddressLine1("G-21,Lohia nagar");    
26.     address1.setCity("Ghaziabad");    
27.     address1.setState("UP");    
28.     address1.setCountry("India");    
29.     address1.setPincode(201301);    
30.         
31.     e1.setAddress(address1);    
32.     address1.setEmployee(e1);    
33.         
34.     session.persist(e1);    
35.     t.commit();    
36.         
37.     session.close();    
38.     System.out.println("success");    
39. }    
40. }    
Output

Fetch.java

1. package com.javatpoint;    
2. import java.util.Iterator;    
3. import java.util.List;  
4.   
5. import javax.persistence.TypedQuery;    
6. import org.hibernate.Session;    
7. import org.hibernate.SessionFactory;  
8. import org.hibernate.boot.Metadata;  
9. import org.hibernate.boot.MetadataSources;  
10. import org.hibernate.boot.registry.StandardServiceRegistry;  
11. import org.hibernate.boot.registry.StandardServiceRegistryBuilder;   
12.     
13. public class Fetch {    
14. public static void main(String[] args) {    
15.     StandardServiceRegistry ssr=new StandardServiceRegistryBuilder().configure("hi
bernate.cfg.xml").build();  
16.     Metadata meta=new MetadataSources(ssr).getMetadataBuilder().build();  
17.       
18.     SessionFactory factory=meta.getSessionFactoryBuilder().build();  
19.     Session session=factory.openSession();  
20.         
21.     TypedQuery query=session.createQuery("from Employee");    
22.     List<Employee> list=query.getResultList();   
23.         
24.     Iterator<Employee> itr=list.iterator();    
25.     while(itr.hasNext()){    
26.      Employee emp=itr.next();    
27.      System.out.println(emp.getEmployeeId()+" "+emp.getName()+" 
"+emp.getEmail());    
28.      Address address=emp.getAddress();    
29.      System.out.println(address.getAddressLine1()+" "+address.getCity()+" "+    
30.         address.getState()+" "+address.getCountry()+" "+address.getPincode());    
31.     }    
32.     
33.     session.close();    
34.     System.out.println("success");    
35. }    
36. }    

Output

Hibernate Many to One Mapping using XML


In many to one mapping, various attributes can be referred to one attribute only.

In this example, every employee has one company address only and one address belongs to
many employees. Here, we are going to perform many to one mapping using XML.

1) Persistent classes for one to one mapping


There are two persistent classes Employee.java and Address.java. Employee class contains
Address class reference and vice versa.

Employee.java
1. package com.javatpoint;    
2.     
3. public class Employee {    
4. private int employeeId;    
5. private String name,email;    
6. private Address address;    
7. //setters and getters    
8. }    

Address.java
1. package com.javatpoint;    
2.     
3. public class Address {    
4. private int addressId;    
5. private String addressLine1,city,state,country;    
6. private int pincode;    
7. private Employee employee;    
8. //setters and getters    
9. }  

2) Mapping files for the persistent classes


The two mapping files are employee.hbm.xml and address.hbm.xml.

employee.hbm.xml
1. <?xml version='1.0' encoding='UTF-8'?>    
2. <!DOCTYPE hibernate-mapping PUBLIC    
3.           "-//Hibernate/Hibernate Mapping DTD 5.3//EN"    
4.           "http://hibernate.sourceforge.net/hibernate-mapping-5.3.dtd">    
5.     
6.           <hibernate-mapping>    
7.           <class name="com.javatpoint.Employee" table="emp22">    
8.           <id name="employeeId">    
9.           <generator class="increment"></generator>    
10.           </id>    
11.           <property name="name"></property>    
12.           <property name="email"></property>    
13.               
14.           <many-to-one name="address" cascade="all"></many-to-one>    
15.           </class>    
16.               
17.           </hibernate-mapping>   

address.hbm.xml
1. <?xml version='1.0' encoding='UTF-8'?>    
2. <!DOCTYPE hibernate-mapping PUBLIC    
3.           "-//Hibernate/Hibernate Mapping DTD 5.3//EN"    
4.           "http://hibernate.sourceforge.net/hibernate-mapping-5.3.dtd">    
5.     
6.           <hibernate-mapping>    
7.           <class name="com.javatpoint.Address" table="address22">    
8.           <id name="addressId">    
9.           <generator class="increment"></generator>    
10.           </id>    
11.           <property name="addressLine1"></property>    
12.           <property name="city"></property>    
13.           <property name="state"></property>    
14.           <property name="country"></property>    
15.           <property name="pincode"></property>    
16.           </class>    
17.           </hibernate-mapping>    

3) Configuration file
This file contains information about the database and mapping file.

1. <?xml version='1.0' encoding='UTF-8'?>    
2. <!DOCTYPE hibernate-configuration PUBLIC    
3.           "-//Hibernate/Hibernate Configuration DTD 5.3//EN"    
4.           "http://hibernate.sourceforge.net/hibernate-configuration-5.3.dtd">    
5.      
6. <hibernate-configuration>    
7.     
8.     <session-factory>    
9.         <property name="hbm2ddl.auto">update</property>    
10.         <property name="dialect">org.hibernate.dialect.Oracle9Dialect</property>    
11.         <property name="connection.url">jdbc:oracle:thin:@localhost:1521:xe</prop
erty>    
12.         <property name="connection.username">system</property>    
13.         <property name="connection.password">jtp</property>    
14.         <property name="connection.driver_class">oracle.jdbc.driver.OracleDriver</pr
operty>    
15.     <mapping resource="employee.hbm.xml"/>    
16.     <mapping resource="address.hbm.xml"/>    
17.     </session-factory>    
18.     
19. </hibernate-configuration>    

4) User classes to store and fetch the data


Store.java
1. package com.javatpoint;    
2.   
3. import org.hibernate.*;  
4. import org.hibernate.boot.Metadata;  
5. import org.hibernate.boot.MetadataSources;  
6. import org.hibernate.boot.registry.StandardServiceRegistry;  
7. import org.hibernate.boot.registry.StandardServiceRegistryBuilder;    
8.     
9. public class Store {    
10. public static void main(String[] args) {    
11.       
12.     StandardServiceRegistry ssr=new StandardServiceRegistryBuilder().configure("hi
bernate.cfg.xml").build();  
13.     Metadata meta=new MetadataSources(ssr).getMetadataBuilder().build();  
14.       
15.     SessionFactory factory=meta.getSessionFactoryBuilder().build();  
16.     Session session=factory.openSession();  
17.       
18.     Transaction t=session.beginTransaction();    
19.         
20.     Employee e1=new Employee();    
21.     e1.setName("Ravi Malik");    
22.     e1.setEmail("[email protected]");    
23.       
24.     Employee e2=new Employee();  
25.     e2.setName("Anuj Verma");  
26.     e2.setEmail("[email protected]");  
27.         
28.     Address address1=new Address();    
29.     address1.setAddressLine1("G-13,Sector 3");    
30.     address1.setCity("Noida");    
31.     address1.setState("UP");    
32.     address1.setCountry("India");    
33.     address1.setPincode(201301);    
34.         
35.     e1.setAddress(address1);    
36.     e2.setAddress(address1);  
37.   
38.     session.persist(e1);    
39.     session.persist(e2);  
40.     t.commit();    
41.         
42.     session.close();    
43.     System.out.println("success");    
44. }    
45. }    

Output

Fetch.java
1. package com.javatpoint;    
2. import java.util.Iterator;    
3. import java.util.List;  
4.   
5. import javax.persistence.TypedQuery;    
6. import org.hibernate.Session;    
7. import org.hibernate.SessionFactory;  
8. import org.hibernate.boot.Metadata;  
9. import org.hibernate.boot.MetadataSources;  
10. import org.hibernate.boot.registry.StandardServiceRegistry;  
11. import org.hibernate.boot.registry.StandardServiceRegistryBuilder;   
12.     
13. public class Fetch {    
14. public static void main(String[] args) {    
15.     StandardServiceRegistry ssr=new StandardServiceRegistryBuilder().configure("hi
bernate.cfg.xml").build();  
16.     Metadata meta=new MetadataSources(ssr).getMetadataBuilder().build();  
17.       
18.     SessionFactory factory=meta.getSessionFactoryBuilder().build();  
19.     Session session=factory.openSession();  
20.         
21.     TypedQuery query=session.createQuery("from Employee e");    
22.     List<Employee> list=query.getResultList();   
23.         
24.     Iterator<Employee> itr=list.iterator();    
25.     while(itr.hasNext()){    
26.      Employee emp=itr.next();    
27.      System.out.println(emp.getEmployeeId()+" "+emp.getName()+" 
"+emp.getEmail());    
28.      Address address=emp.getAddress();    
29.      System.out.println(address.getAddressLine1()+" "+address.getCity()+" "+    
30.         address.getState()+" "+address.getCountry()+" "+address.getPincode());    
31.     }    
32.     
33.     session.close();    
34.     System.out.println("success");    
35. }    
36. }    

Output

Hibernate Many to One Mapping using


Annotation
In many to one mapping, various attributes can be referred to one attribute only.
In this example, every employee has one company address only and one address belongs to
many employees. Here, we are going to perform many to one mapping using annotation.

Let's look at the persistent classes

1) Persistent classes for one to one mapping


There are two persistent classes Employee.java and Address.java. Employee class contains
Address class reference and vice versa.

Employee.java
1. package com.javatpoint;  
2. import javax.persistence.*;  
3.   
4. @Entity  
5. @Table(name="emp107")  
6. public class Employee {    
7.      @Id  
8.      @GeneratedValue(strategy=GenerationType.AUTO)    
9. private int employeeId;    
10. private String name,email;    
11. @ManyToOne(cascade=CascadeType.ALL)  
12. private Address address;  
13. public int getEmployeeId() {  
14.     return employeeId;  
15. }  
16. public void setEmployeeId(int employeeId) {  
17.     this.employeeId = employeeId;  
18. }  
19. public String getName() {  
20.     return name;  
21. }  
22. public void setName(String name) {  
23.     this.name = name;  
24. }  
25. public String getEmail() {  
26.     return email;  
27. }  
28. public void setEmail(String email) {  
29.     this.email = email;  
30. }  
31. public Address getAddress() {  
32.     return address;  
33. }  
34. public void setAddress(Address address) {  
35.     this.address = address;  
36. }    
37. }  

Address.java
1. package com.javatpoint;  
2.   
3. import javax.persistence.*;  
4.   
5. @Entity  
6. @Table(name="address107")  
7. public class Address {  
8.     @Id  
9.     @GeneratedValue(strategy=GenerationType.AUTO)  
10.     private int addressId;    
11.     private String addressLine1,city,state,country;    
12.     private int pincode;    
13.    @OneToOne(cascade=CascadeType.ALL)  
14.     private Employee employee;  
15.     public int getAddressId() {  
16.         return addressId;  
17.     }  
18.     public void setAddressId(int addressId) {  
19.         this.addressId = addressId;  
20.     }  
21.     public String getAddressLine1() {  
22.         return addressLine1;  
23.     }  
24.     public void setAddressLine1(String addressLine1) {  
25.         this.addressLine1 = addressLine1;  
26.     }  
27.     public String getCity() {  
28.         return city;  
29.     }  
30.     public void setCity(String city) {  
31.         this.city = city;  
32.     }  
33.     public String getState() {  
34.         return state;  
35.     }  
36.     public void setState(String state) {  
37.         this.state = state;  
38.     }  
39.     public String getCountry() {  
40.         return country;  
41.     }  
42.     public void setCountry(String country) {  
43.         this.country = country;  
44.     }  
45.     public int getPincode() {  
46.         return pincode;  
47.     }  
48.     public void setPincode(int pincode) {  
49.         this.pincode = pincode;  
50.     }  
51.     public Employee getEmployee() {  
52.         return employee;  
53.     }  
54.     public void setEmployee(Employee employee) {  
55.         this.employee = employee;  
56.     }    
57. }  

2) Add project information and configuration in pom.xml


file.
Open pom.xml file and click source. Now, add the below dependencies between
<dependencies>....</dependencies> tag. These dependencies are used to add the jar files
in Maven project.

1. <dependency>    
2.     <groupId>org.hibernate</groupId>    
3.     <artifactId>hibernate-core</artifactId>    
4.     <version>5.3.1.Final</version>    
5. </dependency>    

1. <dependency>    
2.     <groupId>com.oracle</groupId>    
3.     <artifactId>ojdbc14</artifactId>    
4.     <version>10.2.0.4.0</version>    
5. </dependency>    

3) Configuration file
This file contains information about the database and mapping file.

hibernate.cfg.xml
1. <?xml version='1.0' encoding='UTF-8'?>    
2. <!DOCTYPE hibernate-configuration PUBLIC    
3.           "-//Hibernate/Hibernate Configuration DTD 5.3//EN"    
4.           "http://hibernate.sourceforge.net/hibernate-configuration-5.3.dtd">    
5.      
6. <hibernate-configuration>    
7.     
8.     <session-factory>    
9.         <property name="hbm2ddl.auto">create</property>    
10.         <property name="dialect">org.hibernate.dialect.Oracle9Dialect</property>    
11.         <property name="connection.url">jdbc:oracle:thin:@localhost:1521:xe</prop
erty>    
12.         <property name="connection.username">system</property>    
13.         <property name="connection.password">jtp</property>    
14.         <property name="connection.driver_class">oracle.jdbc.driver.OracleDriver</pr
operty>    
15.     <mapping class="com.javatpoint.Address"/>    
16.     <mapping class="com.javatpoint.Employee"/>    
17.     </session-factory>    
18.     
19. </hibernate-configuration>    

4) User classes to store and fetch the data


Store.java
1. package com.javatpoint;    
2.   
3. import org.hibernate.*;  
4. import org.hibernate.boot.Metadata;  
5. import org.hibernate.boot.MetadataSources;  
6. import org.hibernate.boot.registry.StandardServiceRegistry;  
7. import org.hibernate.boot.registry.StandardServiceRegistryBuilder;    
8.     
9. public class Store {    
10. public static void main(String[] args) {    
11.       
12.     StandardServiceRegistry ssr=new StandardServiceRegistryBuilder().configure("hi
bernate.cfg.xml").build();  
13.     Metadata meta=new MetadataSources(ssr).getMetadataBuilder().build();  
14.       
15.     SessionFactory factory=meta.getSessionFactoryBuilder().build();  
16.     Session session=factory.openSession();  
17.       
18.     Transaction t=session.beginTransaction();    
19.         
20.     Employee e1=new Employee();    
21.     e1.setName("Ravi Malik");    
22.     e1.setEmail("[email protected]");    
23.       
24.     Employee e2=new Employee();  
25.     e2.setName("Anuj Verma");  
26.     e2.setEmail("[email protected]");  
27.         
28.     Address address1=new Address();    
29.     address1.setAddressLine1("G-13,Sector 3");    
30.     address1.setCity("Noida");    
31.     address1.setState("UP");    
32.     address1.setCountry("India");    
33.     address1.setPincode(201301);    
34.         
35.     e1.setAddress(address1);    
36.     e2.setAddress(address1);  
37.   
38.     session.persist(e1);    
39.     session.persist(e2);  
40.     t.commit();    
41.         
42.     session.close();    
43.     System.out.println("success");    
44. }    
45. }    
OUTPUT

Fetch.java
1. package com.javatpoint;    
2. import java.util.Iterator;    
3. import java.util.List;  
4.   
5. import javax.persistence.TypedQuery;    
6. import org.hibernate.Session;    
7. import org.hibernate.SessionFactory;  
8. import org.hibernate.boot.Metadata;  
9. import org.hibernate.boot.MetadataSources;  
10. import org.hibernate.boot.registry.StandardServiceRegistry;  
11. import org.hibernate.boot.registry.StandardServiceRegistryBuilder;   
12.     
13. public class Fetch {    
14. public static void main(String[] args) {    
15.     StandardServiceRegistry ssr=new StandardServiceRegistryBuilder().configure("hi
bernate.cfg.xml").build();  
16.     Metadata meta=new MetadataSources(ssr).getMetadataBuilder().build();  
17.       
18.     SessionFactory factory=meta.getSessionFactoryBuilder().build();  
19.     Session session=factory.openSession();  
20.         
21.     TypedQuery query=session.createQuery("from Employee e");    
22.     List<Employee> list=query.getResultList();   
23.         
24.     Iterator<Employee> itr=list.iterator();    
25.     while(itr.hasNext()){    
26.      Employee emp=itr.next();    
27.      System.out.println(emp.getEmployeeId()+" "+emp.getName()+" 
"+emp.getEmail());    
28.      Address address=emp.getAddress();    
29.      System.out.println(address.getAddressLine1()+" "+address.getCity()+" "+    
30.         address.getState()+" "+address.getCountry()+" "+address.getPincode());    
31.     }    
32.     
33.     session.close();    
34.     System.out.println("success");    
35. }    
36. }    

Output

Output

Hibernate Many to One Mapping using


Annotation
In many to one mapping, various attributes can be referred to one attribute only.

In this example, every employee has one company address only and one address belongs to
many employees. Here, we are going to perform many to one mapping using annotation.

Let's look at the persistent classes

1) Persistent classes for one to one mapping


There are two persistent classes Employee.java and Address.java. Employee class contains
Address class reference and vice versa.

Employee.java
1. package com.javatpoint;  
2. import javax.persistence.*;  
3.   
4. @Entity  
5. @Table(name="emp107")  
6. public class Employee {    
7.      @Id  
8.      @GeneratedValue(strategy=GenerationType.AUTO)    
9. private int employeeId;    
10. private String name,email;    
11. @ManyToOne(cascade=CascadeType.ALL)  
12. private Address address;  
13. public int getEmployeeId() {  
14.     return employeeId;  
15. }  
16. public void setEmployeeId(int employeeId) {  
17.     this.employeeId = employeeId;  
18. }  
19. public String getName() {  
20.     return name;  
21. }  
22. public void setName(String name) {  
23.     this.name = name;  
24. }  
25. public String getEmail() {  
26.     return email;  
27. }  
28. public void setEmail(String email) {  
29.     this.email = email;  
30. }  
31. public Address getAddress() {  
32.     return address;  
33. }  
34. public void setAddress(Address address) {  
35.     this.address = address;  
36. }    
37. }  

Address.java
1. package com.javatpoint;  
2.   
3. import javax.persistence.*;  
4.   
5. @Entity  
6. @Table(name="address107")  
7. public class Address {  
8.     @Id  
9.     @GeneratedValue(strategy=GenerationType.AUTO)  
10.     private int addressId;    
11.     private String addressLine1,city,state,country;    
12.     private int pincode;    
13.    @OneToOne(cascade=CascadeType.ALL)  
14.     private Employee employee;  
15.     public int getAddressId() {  
16.         return addressId;  
17.     }  
18.     public void setAddressId(int addressId) {  
19.         this.addressId = addressId;  
20.     }  
21.     public String getAddressLine1() {  
22.         return addressLine1;  
23.     }  
24.     public void setAddressLine1(String addressLine1) {  
25.         this.addressLine1 = addressLine1;  
26.     }  
27.     public String getCity() {  
28.         return city;  
29.     }  
30.     public void setCity(String city) {  
31.         this.city = city;  
32.     }  
33.     public String getState() {  
34.         return state;  
35.     }  
36.     public void setState(String state) {  
37.         this.state = state;  
38.     }  
39.     public String getCountry() {  
40.         return country;  
41.     }  
42.     public void setCountry(String country) {  
43.         this.country = country;  
44.     }  
45.     public int getPincode() {  
46.         return pincode;  
47.     }  
48.     public void setPincode(int pincode) {  
49.         this.pincode = pincode;  
50.     }  
51.     public Employee getEmployee() {  
52.         return employee;  
53.     }  
54.     public void setEmployee(Employee employee) {  
55.         this.employee = employee;  
56.     }    
57. }  

2) Add project information and configuration in pom.xml


file.
Open pom.xml file and click source. Now, add the below dependencies between
<dependencies>....</dependencies> tag. These dependencies are used to add the jar files
in Maven project.

1. <dependency>    
2.     <groupId>org.hibernate</groupId>    
3.     <artifactId>hibernate-core</artifactId>    
4.     <version>5.3.1.Final</version>    
5. </dependency>    

1. <dependency>    
2.     <groupId>com.oracle</groupId>    
3.     <artifactId>ojdbc14</artifactId>    
4.     <version>10.2.0.4.0</version>    
5. </dependency>    

3) Configuration file
This file contains information about the database and mapping file.

hibernate.cfg.xml
1. <?xml version='1.0' encoding='UTF-8'?>    
2. <!DOCTYPE hibernate-configuration PUBLIC    
3.           "-//Hibernate/Hibernate Configuration DTD 5.3//EN"    
4.           "http://hibernate.sourceforge.net/hibernate-configuration-5.3.dtd">    
5.      
6. <hibernate-configuration>    
7.     
8.     <session-factory>    
9.         <property name="hbm2ddl.auto">create</property>    
10.         <property name="dialect">org.hibernate.dialect.Oracle9Dialect</property>    
11.         <property name="connection.url">jdbc:oracle:thin:@localhost:1521:xe</prop
erty>    
12.         <property name="connection.username">system</property>    
13.         <property name="connection.password">jtp</property>    
14.         <property name="connection.driver_class">oracle.jdbc.driver.OracleDriver</pr
operty>    
15.     <mapping class="com.javatpoint.Address"/>    
16.     <mapping class="com.javatpoint.Employee"/>    
17.     </session-factory>    
18.     
19. </hibernate-configuration>    

4) User classes to store and fetch the data


Store.java
1. package com.javatpoint;    
2.   
3. import org.hibernate.*;  
4. import org.hibernate.boot.Metadata;  
5. import org.hibernate.boot.MetadataSources;  
6. import org.hibernate.boot.registry.StandardServiceRegistry;  
7. import org.hibernate.boot.registry.StandardServiceRegistryBuilder;    
8.     
9. public class Store {    
10. public static void main(String[] args) {    
11.       
12.     StandardServiceRegistry ssr=new StandardServiceRegistryBuilder().configure("hi
bernate.cfg.xml").build();  
13.     Metadata meta=new MetadataSources(ssr).getMetadataBuilder().build();  
14.       
15.     SessionFactory factory=meta.getSessionFactoryBuilder().build();  
16.     Session session=factory.openSession();  
17.       
18.     Transaction t=session.beginTransaction();    
19.         
20.     Employee e1=new Employee();    
21.     e1.setName("Ravi Malik");    
22.     e1.setEmail("[email protected]");    
23.       
24.     Employee e2=new Employee();  
25.     e2.setName("Anuj Verma");  
26.     e2.setEmail("[email protected]");  
27.         
28.     Address address1=new Address();    
29.     address1.setAddressLine1("G-13,Sector 3");    
30.     address1.setCity("Noida");    
31.     address1.setState("UP");    
32.     address1.setCountry("India");    
33.     address1.setPincode(201301);    
34.         
35.     e1.setAddress(address1);    
36.     e2.setAddress(address1);  
37.   
38.     session.persist(e1);    
39.     session.persist(e2);  
40.     t.commit();    
41.         
42.     session.close();    
43.     System.out.println("success");    
44. }    
45. }    

OUTPUT

Fetch.java
1. package com.javatpoint;    
2. import java.util.Iterator;    
3. import java.util.List;  
4.   
5. import javax.persistence.TypedQuery;    
6. import org.hibernate.Session;    
7. import org.hibernate.SessionFactory;  
8. import org.hibernate.boot.Metadata;  
9. import org.hibernate.boot.MetadataSources;  
10. import org.hibernate.boot.registry.StandardServiceRegistry;  
11. import org.hibernate.boot.registry.StandardServiceRegistryBuilder;   
12.     
13. public class Fetch {    
14. public static void main(String[] args) {    
15.     StandardServiceRegistry ssr=new StandardServiceRegistryBuilder().configure("hi
bernate.cfg.xml").build();  
16.     Metadata meta=new MetadataSources(ssr).getMetadataBuilder().build();  
17.       
18.     SessionFactory factory=meta.getSessionFactoryBuilder().build();  
19.     Session session=factory.openSession();  
20.         
21.     TypedQuery query=session.createQuery("from Employee e");    
22.     List<Employee> list=query.getResultList();   
23.         
24.     Iterator<Employee> itr=list.iterator();    
25.     while(itr.hasNext()){    
26.      Employee emp=itr.next();    
27.      System.out.println(emp.getEmployeeId()+" "+emp.getName()+" 
"+emp.getEmail());    
28.      Address address=emp.getAddress();    
29.      System.out.println(address.getAddressLine1()+" "+address.getCity()+" "+    
30.         address.getState()+" "+address.getCountry()+" "+address.getPincode());    
31.     }    
32.     
33.     session.close();    
34.     System.out.println("success");    
35. }    
36. }    

Output
Output

idirectional Association
Bidirectional association allows us to fetch details of dependent object from both side. In
such case, we have the reference of two classes in each other.

Let's take an example of Employee and Address, if Employee class has-a reference of
Address and Address has a reference of Employee. Additionally, you have applied one-to-
one or one-to-many relationship for the classes in mapping file as well, it is known as
bidirectional association.

Visit our one-to-one and one-to-many mapping pages to learn about it.

Hibernate Lazy Collection


Lazy collection loads the child objects on demand, it is used to improve performance. Since
Hibernate 3.0, lazy collection is enabled by default.

To use lazy collection, you may optionally use lazy="true" attribute in your collection. It is
by default true, so you don't need to do this. If you set it to false, all the child objects will
be loaded initially which will decrease performance in case of big data.

Let's see the hibernate mapping file where we have used lazy="true" attribute.

1. <list name="answers" lazy="true">  
2.           <key column="qid"></key>  
3.           <index column="type"></index>  
4.           <one-to-many class="com.javatpoint.Answer"/>  
5. </list>  
Component Mapping
1. Component Mapping
2. Example of Component Mapping

In component mapping, we will map the dependent object as a component. An component


is an object that is stored as an value rather than entity reference. This is mainly used if the
dependent object doen't have primary key. It is used in case of composition (HAS-A
relation), that is why it is termed as component. Let's see the class that have HAS-A
relationship.

1. package com.javatpoint;  
2.   
3. public class Address {  
4. private String city,country;  
5. private int pincode;  
6.   
7. //getters and setters  
8. }  
1. package com.javatpoint;  
2. public class Employee {  
3. private int id;  
4. private String name;  
5. private Address address;//HAS-A  
6.   
7. //getters and setters  
8. }  

Here, address is a dependent object. Hibernate framework provides the facility to map the
dependent object as a component. Let's see how can we map this dependent object in
mapping file.

1. ...  
2. <class name="com.javatpoint.Employee" table="emp177">  
3. <id name="id">  
4. <generator class="increment"></generator>  
5. </id>  
6. <property name="name"></property>  
7.   
8. <component name="address" class="com.javatpoint.Address">  
9. <property name="city"></property>  
10. <property name="country"></property>  
11. <property name="pincode"></property>  
12. </component>  
13.   
14. </class>  
15. ...  

Let's see the data of the emp177 table.

Hibernate Transaction Management Example


1. Understanding Transaction
2. ACID Property
3. Hibernate Transaction Management

A transaction simply represents a unit of work. In such case, if one step fails, the whole
transaction fails (which is termed as atomicity). A transaction can be described by ACID
properties (Atomicity, Consistency, Isolation and Durability).

Transaction Interface in Hibernate


In hibernate framework, we have Transaction interface that defines the unit of work. It
maintains abstraction from the transaction implementation (JTA,JDBC).

A transaction is associated with Session and instantiated by


calling session.beginTransaction().

The methods of Transaction interface are as follows:

1. void begin() starts a new transaction.


2. void commit() ends the unit of work unless we are in FlushMode.NEVER.
3. void rollback() forces this transaction to rollback.
4. void setTimeout(int seconds) it sets a transaction timeout for any transaction
started by a subsequent call to begin on this instance.
5. boolean isAlive() checks if the transaction is still alive.
6. void registerSynchronization(Synchronization s) registers a user
synchronization callback for this transaction.
7. boolean wasCommited() checks if the transaction is commited successfully.
8. boolean wasRolledBack() checks if the transaction is rolledback successfully.

Example of Transaction Management in Hibernate


In hibernate, it is better to rollback the transaction if any exception occurs, so that
resources can be free. Let's see the example of transaction management in hibernate.

1. Session session = null;  
2. Transaction tx = null;  
3.   
4. try {  
5. session = sessionFactory.openSession();  
6. tx = session.beginTransaction();  
7. //some action  
8.   
9. tx.commit();  
10.   
11. }catch (Exception ex) {  
12. ex.printStackTrace();  
13. tx.rollback();  
14. }  
15. finally {session.close();}  
Hibernate Query Language (HQL)
1. Hibernate Query Language
2. Advantage of HQL
3. Query Interface

Hibernate Query Language (HQL) is same as SQL (Structured Query Language) but it
doesn't depends on the table of the database. Instead of table name, we use class name in
HQL. So it is database independent query language.

Advantage of HQL
There are many advantages of HQL. They are as follows:

o database independent
o supports polymorphic queries
o easy to learn for Java Programmer

Query Interface
It is an object oriented representation of Hibernate Query. The object of Query can be
obtained by calling the createQuery() method Session interface.

The query interface provides many methods. There is given commonly used methods:

1. public int executeUpdate() is used to execute the update or delete query.


2. public List list() returns the result of the ralation as a list.
3. public Query setFirstResult(int rowno) specifies the row number from where
record will be retrieved.
4. public Query setMaxResult(int rowno) specifies the no. of records to be
retrieved from the relation (table).
5. public Query setParameter(int position, Object value) it sets the value to the
JDBC style query parameter.
6. public Query setParameter(String name, Object value) it sets the value to a
named query parameter.

Example of HQL to get all the records


1. Query query=session.createQuery("from Emp");//here persistent class name is Emp  
2. List list=query.list();  

Example of HQL to get records with pagination


1. Query query=session.createQuery("from Emp");  
2. query.setFirstResult(5);  
3. query.setMaxResult(10);  
4. List list=query.list();//will return the records from 5 to 10th number  

Example of HQL update query


1. Transaction tx=session.beginTransaction();  
2. Query q=session.createQuery("update User set name=:n where id=:i");  
3. q.setParameter("n","Udit Kumar");  
4. q.setParameter("i",111);  
5.   
6. int status=q.executeUpdate();  
7. System.out.println(status);  
8. tx.commit();  

Example of HQL delete query


1. Query query=session.createQuery("delete from Emp where id=100");  
2. //specifying class name (Emp) not tablename  
3. query.executeUpdate();  

HQL with Aggregate functions


You may call avg(), min(), max() etc. aggregate functions by HQL. Let's see some common
examples:

Example to get total salary of all the employees


1. Query q=session.createQuery("select sum(salary) from Emp");  
2. List<Integer> list=q.list();  
3. System.out.println(list.get(0));  
Example to get maximum salary of employee
1. Query q=session.createQuery("select max(salary) from Emp");  

Example to get minimum salary of employee


1. Query q=session.createQuery("select min(salary) from Emp");  

Example to count total number of employee ID


1. Query q=session.createQuery("select count(id) from Emp");  

Example to get average salary of each employees


1. Query q=session.createQuery("select avg(salary) from Emp");  

HCQL (Hibernate Criteria Query Language)


1. Hibernate Criteria Query Language
2. Criteria Interface
3. Restrictions class
4. Examples of HCQL

The Hibernate Criteria Query Language (HCQL) is used to fetch the records based on the
specific criteria. The Criteria interface provides methods to apply criteria such as retreiving
all the records of table whose salary is greater than 50000 etc.

Advantage of HCQL
The HCQL provides methods to add criteria, so it is easy for the java programmer to add
criteria. The java programmer is able to add many criteria on a query.

Criteria Interface
The Criteria interface provides many methods to specify criteria. The object of Criteria can
be obtained by calling the createCriteria() method of Session interface.
Syntax of createCriteria() method of Session interface
1. public Criteria createCriteria(Class c)  

The commonly used methods of Criteria interface are as follows:

1. public Criteria add(Criterion c) is used to add restrictions.


2. public Criteria addOrder(Order o) specifies ordering.
3. public Criteria setFirstResult(int firstResult) specifies the first number of record
to be retreived.
4. public Criteria setMaxResult(int totalResult) specifies the total number of
records to be retreived.
5. public List list() returns list containing object.
6. public Criteria setProjection(Projection projection) specifies the projection.

Restrictions class
Restrictions class provides methods that can be used as Criterion. The commonly used
methods of Restrictions class are as follows:

1. public static SimpleExpression lt(String propertyName,Object value) sets


the less than constraint to the given property.
2. public static SimpleExpression le(String propertyName,Object value) sets
the less than or equal constraint to the given property.
3. public static SimpleExpression gt(String propertyName,Object value) sets
the greater than constraint to the given property.
4. public static SimpleExpression ge(String propertyName,Object value) sets
the greater than or equal than constraint to the given property.
5. public static SimpleExpression ne(String propertyName,Object value) sets
the not equal constraint to the given property.
6. public static SimpleExpression eq(String propertyName,Object value) sets
the equal constraint to the given property.
7. public static Criterion between(String propertyName, Object low, Object
high) sets the between constraint.
8. public static SimpleExpression like(String propertyName, Object value) sets
the like constraint to the given property.
Order class
The Order class represents an order. The commonly used methods of Restrictions class are
as follows:

1. public static Order asc(String propertyName) applies the ascending order on


the basis of given property.
2. public static Order desc(String propertyName) applies the descending order on
the basis of given property.

Examples of Hibernate Criteria Query Language


There are given a lot of examples of HCQL.

Example of HCQL to get all the records


1. Crietria c=session.createCriteria(Emp.class);//passing Class class argument  
2. List list=c.list();  

Example of HCQL to get the 10th to 20th record


1. Crietria c=session.createCriteria(Emp.class);  
2. c.setFirstResult(10);  
3. c.setMaxResult(20);  
4. List list=c.list();  

Example of HCQL to get the records whose salary is greater


than 10000
1. Crietria c=session.createCriteria(Emp.class);  
2. c.add(Restrictions.gt("salary",10000));//salary is the propertyname  
3. List list=c.list();  

Example of HCQL to get the records in ascending order on the


basis of salary
1. Crietria c=session.createCriteria(Emp.class);  
2. c.addOrder(Order.asc("salary"));  
3. List list=c.list();  

HCQL with Projection


We can fetch data of a particular column by projection such as name etc. Let's see the
simple example of projection that prints data of NAME column of the table only.

1. Criteria c=session.createCriteria(Emp.class);  
2. c.setProjection(Projections.property("name"));  
3. List list=c.list();  

Hibernate Named Query


1. Hibernate Named Query
2. Hibernate Named Query by annotation
3. Example of Hibernate Named Query by annotation
4. Hibernate Named Query by mapping file

The hibernate named query is way to use any query by some meaningful name. It is like
using alias names. The Hibernate framework provides the concept of named queries so that
application programmer need not to scatter queries to all the java code.

There are two ways to define the named query in hibernate:

o by annotation
o by mapping file.

Hibernate Named Query by annotation


If you want to use named query in hibernate, you need to have knowledge of
@NamedQueries and @NamedQuery annotations.

@NameQueries annotation is used to define the multiple named queries.

@NameQuery annotation is used to define the single named query.

Let's see the example of using the named queries:


1. @NamedQueries(  
2.     {  
3.         @NamedQuery(  
4.         name = "findEmployeeByName",  
5.         query = "from Employee e where e.name = :name"  
6.         )  
7.     }  
8. )  

Example of Hibernate Named Query by annotation


In this example, we are using annotations to defined the named query in the persistent
class. There are three files only:

o Employee.java
o hibernate.cfg.xml
o FetchDemo

In this example, we are assuming that there is em table in the database containing 4
columns id, name, job and salary and there are some records in this table.

Employee.java

It is a persistent class that uses annotations to define named query and marks this class as
entity.

1. package com.javatpoint;  
2.   
3. import javax.persistence.*;  
4. import javax.persistence.Entity;  
5. import javax.persistence.GeneratedValue;  
6. import javax.persistence.Id;  
7.   
8. @NamedQueries(  
9.     {  
10.         @NamedQuery(  
11.         name = "findEmployeeByName",  
12.         query = "from Employee e where e.name = :name"  
13.         )  
14.     }  
15. )  
16.   
17. @Entity  
18. @Table(name="em")  
19. public class Employee {  
20.       
21.     public String toString(){return id+" "+name+" "+salary+" "+job;}  
22.       
23.     int id;  
24.     String name;  
25.     int salary;  
26.     String job;  
27.     @Id  
28.     @GeneratedValue(strategy=GenerationType.AUTO)  
29.        
30.     //getters and setters  
31. }  

hibernate.cfg.xml

It is a configuration file that stores the informations about database such as driver class,
url, username, password and mapping class etc.

1. <?xml version='1.0' encoding='UTF-8'?>  
2. <!DOCTYPE hibernate-configuration PUBLIC  
3.           "-//Hibernate/Hibernate Configuration DTD 5.3//EN"  
4.           "http://hibernate.sourceforge.net/hibernate-configuration-5.3.dtd">  
5.   
6. <hibernate-configuration>  
7.   
8.     <session-factory>  
9.         <property name="hbm2ddl.auto">update</property>  
10.         <property name="dialect">org.hibernate.dialect.Oracle9Dialect</property>  
11.         <property name="connection.url">jdbc:oracle:thin:@localhost:1521:xe</prop
erty>  
12.         <property name="connection.username">system</property>  
13.         <property name="connection.password">jtp</property>  
14.         <property name="connection.driver_class">oracle.jdbc.driver.OracleDriver</pr
operty>  
15.     <mapping class="com.javatpoint.Employee"/>  
16.     </session-factory>  
17.   
18. </hibernate-configuration>  

FetchData.java

It is a java class that uses the named query and prints the informations based on the query.
The getNamedQuery method uses the named query and returns the instance of Query.

1. package com.javatpoint;    
2.     
3. import java.util.*;  
4. import javax.persistence.*;  
5. import org.hibernate.*;  
6. import org.hibernate.boot.Metadata;  
7. import org.hibernate.boot.MetadataSources;  
8. import org.hibernate.boot.registry.StandardServiceRegistry;  
9. import org.hibernate.boot.registry.StandardServiceRegistryBuilder;  
10.     
11. public class Fetch {    
12. public static void main(String[] args) {    
13.     
14.      StandardServiceRegistry ssr=new StandardServiceRegistryBuilder().configure("hi
bernate.cfg.xml").build();  
15.         Metadata meta=new MetadataSources(ssr).getMetadataBuilder().build();  
16.           
17.         SessionFactory factory=meta.getSessionFactoryBuilder().build();  
18.         Session session=factory.openSession();  
19.                     
20.     //Hibernate Named Query    
21.            TypedQuery query = session.getNamedQuery("findEmployeeByName");    
22.             query.setParameter("name","amit");   
23.                     
24.             List<Employee> employees=query.getResultList();   
25.             
26.     Iterator<Employee> itr=employees.iterator();    
27.      while(itr.hasNext()){    
28.     Employee e=itr.next();    
29.     System.out.println(e);    
30.      }    
31.     session.close();     
32.   }    
33. }    
Download this hibernate example (Developed using Eclipse IDE)

Hibernate Named Query by mapping file


If want to define named query by mapping file, you need to use query element of
hibernate-mapping to define the named query.

In such case, you need to create hbm file that defines the named query. Other resources
are same as given in the above example except Persistent class Employee.java where you
don't need to use any annotation and hibernate.cfg.xml file where you need to specify
mapping resource of the hbm file.

The hbm file should be like this:

emp.hbm.xml
1. <?xml version='1.0' encoding='UTF-8'?>  
2. <!DOCTYPE hibernate-mapping PUBLIC  
3.           "-//Hibernate/Hibernate Mapping DTD 5.3//EN"  
4.           "http://hibernate.sourceforge.net/hibernate-mapping-5.3.dtd">  
5.   
6. <hibernate-mapping>  
7. <class name="com.javatpoint.Employee" table="em">  
8. <id name="id">  
9. <generator class="native"></generator>  
10. </id>  
11. <property name="name"></property>  
12. <property name="job"></property>  
13. <property name="salary"></property>  
14. </class>  
15.   
16. <query name="findEmployeeByName">  
17. <![CDATA[from Employee e where e.name = :name]]>  
18. </query>  
19.    
20. </hibernate-mapping>  

The persistent class should be like this:

Employee.java
1. package com.javatpoint;  
2. public class Employee {  
3.     int id;  
4.     String name;  
5.     int salary;  
6.     String job;  
7.     //getters and setters  
8. }  

Now include the mapping resource in the hbm file as:

hibernate.cfg.xml
1. <mapping resource="emp.hbm.xml"/>  

Caching in Hibernate
1. Caching in Hibernate
2. First Level Cache
3. Second Level Cache

Hibernate caching improves the performance of the application by pooling the object in the
cache. It is useful when we have to fetch the same data multiple times.

There are mainly two types of caching: first level cache and second level cache.

First Level Cache

Session object holds the first level cache data. It is enabled by default. The first level cache
data will not be available to entire application. An application can use many session object.

Second Level Cache

SessionFactory object holds the second level cache data. The data stored in the second level
cache will be available to entire application. But we need to enable it explicitely.

Hibernate Second Level Cache


Hibernate second level cache uses a common cache for all the session object of a
session factory. It is useful if you have multiple session objects from a session factory.

SessionFactory holds the second level cache data. It is global for all the session objects
and not enabled by default.
Different vendors have provided the implementation of Second Level Cache.

1. EH Cache
2. OS Cache
3. Swarm Cache
4. JBoss Cache

Each implementation provides different cache usage functionality. There are four ways to
use second level cache.

1. read-only: caching will work for read only operation.


2. nonstrict-read-write: caching will work for read and write but one at a time.
3. read-write: caching will work for read and write, can be used simultaneously.
4. transactional: caching will work for transaction.

The cache-usage property can be applied to class or collection level in hbm.xml file. The
example to define cache usage is given below:

1. <cache usage="read-only" />  

Let's see the second level cache implementation and cache usage.

Implementation read-only nonstrict-read-write

EH Cache Yes Yes

OS Cache Yes Yes

Swarm Cache Yes Yes

JBoss Cache No No

Hibernate Second Level Cache Example


To understand the second level cache through example, we need to follow the following
steps:
1. Create the persistent class using Maven
2. Add project information and configuration in pom.xml file
3. Create the Configuration file
4. Create the class that retrieves the persistent object.

Here, we are assuming, there is emp1012 table in the oracle database containing some records.

1) Create the persistent class using Maven.


File: Employee.java

1. package com.javatpoint;    
2. import javax.persistence.*;  
3. import org.hibernate.annotations.Cache;  
4. import org.hibernate.annotations.CacheConcurrencyStrategy;  
5. @Entity  
6. @Table(name="emp1012")  
7. @Cacheable  
8. @Cache(usage=CacheConcurrencyStrategy.READ_ONLY)  
9. public class Employee {    
10.     @Id  
11. private int id;    
12. private String name;    
13. private float salary;    
14.     
15. public Employee() {}    
16. public Employee(String name, float salary) {    
17.     super();    
18.     this.name = name;    
19.     this.salary = salary;    
20. }  
21. public int getId() {  
22.     return id;  
23. }  
24. public void setId(int id) {  
25.     this.id = id;  
26. }  
27. public String getName() {  
28.     return name;  
29. }  
30. public void setName(String name) {  
31.     this.name = name;  
32. }  
33. public float getSalary() {  
34.     return salary;  
35. }  
36. public void setSalary(float salary) {  
37.     this.salary = salary;  
38. }    
39. }    

2) Add project information and configuration in pom.xml file.


Open pom.xml file and click source. Now, add the below dependencies between
<dependencies>....</dependencies> tag.

1.   <dependency>  
2.     <groupId>org.hibernate</groupId>  
3.     <artifactId>hibernate-core</artifactId>  
4.     <version>5.2.16.Final</version>  
5. </dependency>  
6.       
7. <dependency>  
8.     <groupId>com.oracle</groupId>  
9.     <artifactId>ojdbc14</artifactId>  
10.     <version>10.2.0.4.0</version>  
11. </dependency>  
12.       
13. <dependency>  
14.     <groupId>net.sf.ehcache</groupId>  
15.     <artifactId>ehcache</artifactId>  
16.     <version>2.10.3</version>  
17. </dependency>  
18.       
19.      
20. <dependency>  
21.     <groupId>org.hibernate</groupId>  
22.     <artifactId>hibernate-ehcache</artifactId>  
23.     <version>5.2.16.Final</version>  
24. </dependency>  

3) Create the Configuration file


File: hibernate.cfg.xml

1. <?xml version='1.0' encoding='UTF-8'?>    
2. <!DOCTYPE hibernate-configuration PUBLIC    
3.           "-//Hibernate/Hibernate Configuration DTD 5.2.0//EN"    
4.           "http://hibernate.sourceforge.net/hibernate-configuration-5.2.0.dtd">    
5.     
6. <hibernate-configuration>    
7.     
8.     <session-factory>    
9.         <property name="show_sql">true</property>    
10.         <property name="hbm2ddl.auto">update</property>    
11.         <property name="dialect">org.hibernate.dialect.Oracle9Dialect</property> 
   
12.         <property name="connection.url">jdbc:oracle:thin:@localhost:1521:xe</pr
operty>    
13.         <property name="connection.username">system</property>    
14.         <property name="connection.password">jtp</property>    
15.         <property name="connection.driver_class">oracle.jdbc.driver.OracleDriver</
property>    
16.          
17.          <property name="cache.use_second_level_cache">true</property>   
18.          <property name="cache.region.factory_class">org.hibernate.cache.ehcache.
EhCacheRegionFactory</property>  
19.          <mapping class="com.javatpoint.Employee"/>  
20.     </session-factory>    
21. </hibernate-configuration>    

To implement second level cache, we need to define cache.provider_class property in the


configuration file.

4) Create the class that retrieves the persistent object.


File: FetchTest.java
1. package com.javatpoint;    
2.     
3. import org.hibernate.Session;    
4. import org.hibernate.SessionFactory;  
5. import org.hibernate.boot.Metadata;  
6. import org.hibernate.boot.MetadataSources;  
7. import org.hibernate.boot.registry.StandardServiceRegistry;  
8. import org.hibernate.boot.registry.StandardServiceRegistryBuilder;  
9.     
10. public class FetchTest {    
11. public static void main(String[] args) {    
12.     StandardServiceRegistry ssr=new StandardServiceRegistryBuilder().configure("hi
bernate.cfg.xml").build();  
13.     Metadata meta=new MetadataSources(ssr).getMetadataBuilder().build();  
14.       
15.     SessionFactory factory=meta.getSessionFactoryBuilder().build();  
16.         
17.     Session session1=factory.openSession();    
18.     Employee emp1=(Employee)session1.load(Employee.class,121);    
19.     System.out.println(emp1.getId()+" "+emp1.getName()+" "+emp1.getSalary());   
 
20.     session1.close();    
21.         
22.     Session session2=factory.openSession();    
23.     Employee emp2=(Employee)session2.load(Employee.class,121);    
24.     System.out.println(emp2.getId()+" "+emp2.getName()+" "+emp2.getSalary());   
 
25.     session2.close();    
26.         
27. }    
28. }    

Output:

As we can see here, hibernate does not fire query twice. If you don't use second level
cache, hibernate will fire query twice because both query uses different session objects.

Hibernate and Struts 2 Integration


1. Hibernate and Struts2 Integration
2. Example of Hibernate and struts2 integration

We can integrate any struts application with hibernate. There is no requirement of extra


efforts.

In this example, we going to use struts 2 framework with hibernate. You need to have jar
files for struts 2 and hibernate.

Example of Hibernate and struts2 integration


In this example, we are creating the registration form using struts2 and storing this data
into the database using Hibernate. Let's see the files that we should create to integrate the
struts2 application with hibernate.

o index.jsp file to get input from the user.


o User.java A action class for handling the request. It uses the dao class to store the
data.
o RegisterDao.java A java class that uses DAO design pattern to store the data using
hibernate.
o user.hbm.xml A mapping file that contains information about the persistent class.
In this case, action class works as the persistent class.
o hibernate.cfg.xml A configuration file that contains informations about the
database and mapping file.
o struts.xml file contains information about the action class and result page to be
invoked.
o welcome.jsp A jsp file that displays the welcome information with username.
o web.xml A web.xml file that contains information about the Controller of Struts
framework.

index.jsp

In this page, we have created a form using the struts tags. The action name for this form is
register.

1. <%@ taglib uri="/struts-tags" prefix="S" %>  
2.   
3. <S:form action="register">  
4. <S:textfield name="name" label="Name"></S:textfield>  
5. <S:submit value="register"></S:submit>  
6.   
7. </S:form>  

User.java

It is a simple POJO class. Here it works as the action class for struts and persistent class for
hibernate. It calls the register method of RegisterDao class and returns success as the
string.

1. package com.javatpoint;  
2.   
3. public class User {  
4. private int id;  
5. private String name;  
6. //getters and setters  
7.   
8. public String execute(){  
9.     RegisterDao.saveUser(this);  
10.     return "success";  
11. }  
12.   
13. }  

RegisterDao.java

It is a java class that saves the object of User class using the Hibernate framework.

1. package com.javatpoint;  
2.   
3. import org.hibernate.Session;  
4. import org.hibernate.Transaction;  
5. import org.hibernate.cfg.Configuration;  
6.   
7. public class RegisterDao {  
8.   
9. public static int saveUser(User u){  
10.           
11. Session session=new Configuration().  
12. configure("hibernate.cfg.xml").buildSessionFactory().openSession();  
13.           
14. Transaction t=session.beginTransaction();  
15. int i=(Integer)session.save(u);  
16. t.commit();  
17. session.close();  
18.           
19. return i;  
20.   
21. }  
22.   
23. }  

user.hbm.xml

This mapping file contains all the information of the persitent class.

1. <?xml version='1.0' encoding='UTF-8'?>  
2. <!DOCTYPE hibernate-mapping PUBLIC  
3. "-//Hibernate/Hibernate Mapping DTD 3.0//EN"  
4. "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">  
5.   
6. <hibernate-mapping>  
7. <class name="com.javatpoint.User" table="user451">  
8. <id name="id">  
9. <generator class="increment"></generator>  
10. </id>  
11. <property name="name"></property>  
12. </class>  
13.             
14. </hibernate-mapping>  

hibernate.cfg.xml

This configuration file contains informations about the database and mapping file. Here, we
are using the hb2ddl.auto property, so you don't need to create the table in the database.

1. <?xml version='1.0' encoding='UTF-8'?>  
2. <!DOCTYPE hibernate-configuration PUBLIC  
3.           "-//Hibernate/Hibernate Configuration DTD 3.0//EN"  
4.           "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">  
5.   
6. <!-- Generated by MyEclipse Hibernate Tools.                   -->  
7. <hibernate-configuration>  
8.   
9. <session-factory>  
10. <property name="hbm2ddl.auto">update</property>  
11. <property name="dialect">org.hibernate.dialect.Oracle9Dialect</property>  
12. <property name="connection.url">jdbc:oracle:thin:@localhost:1521:xe</property>  
13. <property name="connection.username">system</property>  
14. <property name="connection.password">oracle</property>  
15. <property name="connection.driver_class">oracle.jdbc.driver.OracleDriver</propert
y>  
16. <mapping resource="user.hbm.xml"/>  
17.       
18. </session-factory>  
19.   
20. </hibernate-configuration>  

struts.xml

This files contains information about the action class to be invoked. Here the action class is
User.

1. <?xml version="1.0" encoding="UTF-8" ?>  
2. <!DOCTYPE struts PUBLIC "-//Apache Software Foundation  
3. //DTD Struts Configuration 2.1//EN"   
4. "http://struts.apache.org/dtds/struts-2.1.dtd">  
5. <struts>  
6.   
7. <package name="abc" extends="struts-default">  
8. <action name="register" class="com.javatpoint.User">  
9. <result name="success">welcome.jsp</result>  
10. </action>  
11. </package>  
12. </struts>      

welcome.jsp

It is the welcome file, that displays the welcome message with username.

1. <%@ taglib uri="/struts-tags" prefix="S" %>  
2.   
3. Welcome: <S:property value="name"/>  
web.xml

It is web.xml file that contains the information about the controller. In case of Struts2,
StrutsPrepareAndExecuteFilter class works as the controller.

1. <?xml version="1.0" encoding="UTF-8"?>  
2. <web-app version="2.5"   
3.     xmlns="http://java.sun.com/xml/ns/javaee"   
4.     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"   
5.     xsi:schemaLocation="http://java.sun.com/xml/ns/javaee   
6.     http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">  
7.   <welcome-file-list>  
8.     <welcome-file>index.jsp</welcome-file>  
9.   </welcome-file-list>  
10.   <filter>  
11.     <filter-name>struts2</filter-name>  
12.     <filter-class>  
13.   org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter  
14.     </filter-class>  
15.   </filter>  
16.   <filter-mapping>  
17.     <filter-name>struts2</filter-name>  
18.     <url-pattern>/*</url-pattern>  
19.   </filter-mapping>  
20. </web-app>  

Hibernate and Spring Integration


We can simply integrate hibernate application with spring application.

In hibernate framework, we provide all the database information hibernate.cfg.xml file.

But if we are going to integrate the hibernate application with spring, we don't need to
create the hibernate.cfg.xml file. We can provide all the information in the
applicationContext.xml file.

Advantage of Spring framework with hibernate


The Spring framework provides HibernateTemplate class, so you don't need to follow so
many steps like create Configuration, BuildSessionFactory, Session, beginning and
committing transaction etc.
So it saves a lot of code.

Understanding problem without using spring:

Let's understand it by the code of hibernate given below:

1. //creating configuration  
2. Configuration cfg=new Configuration();    
3. cfg.configure("hibernate.cfg.xml");    
4.     
5. //creating seession factory object    
6. SessionFactory factory=cfg.buildSessionFactory();    
7.     
8. //creating session object    
9. Session session=factory.openSession();    
10.     
11. //creating transaction object    
12. Transaction t=session.beginTransaction();    
13.         
14. Employee e1=new Employee(111,"arun",40000);    
15. session.persist(e1);//persisting the object    
16.     
17. t.commit();//transaction is commited    
18. session.close();    

As you can see in the code of sole hibernate, you have to follow so many steps.

Solution by using HibernateTemplate class of Spring Framework:

Now, you don't need to follow so many steps. You can simply write this:

1. Employee e1=new Employee(111,"arun",40000);    
2. hibernateTemplate.save(e1);  

Methods of HibernateTemplate class


Let's see a list of commonly used methods of HibernateTemplate class.

No. Method Description


1) void persist(Object entity) persists the given object.

2) Serializable save(Object entity) persists the given object and returns id.

3) void saveOrUpdate(Object entity) persists or updates the given object. If id

4) void update(Object entity) updates the given object.

5) void delete(Object entity) deletes the given object on the basis of id.

6) Object get(Class entityClass, Serializable id) returns the persistent object on the basis

7) Object load(Class entityClass, Serializable id) returns the persistent object on the basis

8) List loadAll(Class entityClass) returns the all the persistent objects.

Steps
Let's see what are the simple steps for hibernate and spring integration:

1. create table in the database It is optional.


2. create applicationContext.xml file It contains information of DataSource,
SessionFactory etc.
3. create Employee.java file It is the persistent class
4. create employee.hbm.xml file It is the mapping file.
5. create EmployeeDao.java file It is the dao class that uses HibernateTemplate.
6. create InsertTest.java file It calls methods of EmployeeDao class.

Example of Hibernate and spring integration


In this example, we are going to integrate the hibernate application with spring. Let's see
the directory structure of spring and hibernate example.
1) create the table in the database

In this example, we are using the Oracle as the database, but you may use any database.
Let's create the table in the oracle database

1. CREATE TABLE  "EMP558"   
2.    (    "ID" NUMBER(10,0) NOT NULL ENABLE,   
3.     "NAME" VARCHAR2(255 CHAR),   
4.     "SALARY" FLOAT(126),   
5.      PRIMARY KEY ("ID") ENABLE  
6.    )  
7. /  

2) Employee.java

It is a simple POJO class. Here it works as the persistent class for hibernate.

1. package com.javatpoint;  
2.   
3. public class Employee {  
4. private int id;  
5. private String name;  
6. private float salary;  
7.   
8. //getters and setters  
9.   
10. }  

3) employee.hbm.xml

This mapping file contains all the information of the persistent class.

1. <?xml version='1.0' encoding='UTF-8'?>  
2. <!DOCTYPE hibernate-mapping PUBLIC  
3. "-//Hibernate/Hibernate Mapping DTD 3.0//EN"  
4. "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">  
5.   
6. <hibernate-mapping>  
7. <class name="com.javatpoint.Employee" table="emp558">  
8.           <id name="id">  
9.           <generator class="assigned"></generator>  
10.           </id>  
11.             
12.           <property name="name"></property>  
13.           <property name="salary"></property>  
14. </class>  
15.             
16. </hibernate-mapping>  

4) EmployeeDao.java

It is a java class that uses the HibernateTemplate class method to persist the object of


Employee class.

1. package com.javatpoint;  
2. import org.springframework.orm.hibernate3.HibernateTemplate;  
3. import java.util.*;  
4. public class EmployeeDao {  
5. HibernateTemplate template;  
6. public void setTemplate(HibernateTemplate template) {  
7.     this.template = template;  
8. }  
9. //method to save employee  
10. public void saveEmployee(Employee e){  
11.     template.save(e);  
12. }  
13. //method to update employee  
14. public void updateEmployee(Employee e){  
15.     template.update(e);  
16. }  
17. //method to delete employee  
18. public void deleteEmployee(Employee e){  
19.     template.delete(e);  
20. }  
21. //method to return one employee of given id  
22. public Employee getById(int id){  
23.     Employee e=(Employee)template.get(Employee.class,id);  
24.     return e;  
25. }  
26. //method to return all employees  
27. public List<Employee> getEmployees(){  
28.     List<Employee> list=new ArrayList<Employee>();  
29.     list=template.loadAll(Employee.class);  
30.     return list;  
31. }  
32. }  

5) applicationContext.xml

In this file, we are providing all the informations of the database in


the BasicDataSource object. This object is used in the LocalSessionFactoryBean class
object, containing some other informations such as mappingResources and
hibernateProperties. The object of LocalSessionFactoryBean class is used in the
HibernateTemplate class. Let's see the code of applicationContext.xml file.
File: applicationContext.xml

1. <?xml version="1.0" encoding="UTF-8"?>  
2. <beans  
3.     xmlns="http://www.springframework.org/schema/beans"  
4.     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
5.     xmlns:p="http://www.springframework.org/schema/p"  
6.     xsi:schemaLocation="http://www.springframework.org/schema/beans  
7.         http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">  
8.   
9.   
10.     <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">  
11.         <property name="driverClassName"  value="oracle.jdbc.driver.OracleDriver">
</property>  
12.         <property name="url" value="jdbc:oracle:thin:@localhost:1521:xe"></propert
y>  
13.         <property name="username" value="system"></property>  
14.         <property name="password" value="oracle"></property>  
15.     </bean>  
16.       
17.     <bean id="mysessionFactory"  class="org.springframework.orm.hibernate3.Local
SessionFactoryBean">  
18.         <property name="dataSource" ref="dataSource"></property>  
19.           
20.         <property name="mappingResources">  
21.         <list>  
22.         <value>employee.hbm.xml</value>  
23.         </list>  
24.         </property>  
25.           
26.         <property name="hibernateProperties">  
27.             <props>  
28.                 <prop key="hibernate.dialect">org.hibernate.dialect.Oracle9Dialect</pro
p>  
29.                 <prop key="hibernate.hbm2ddl.auto">update</prop>  
30.                 <prop key="hibernate.show_sql">true</prop>  
31.                   
32.             </props>  
33.         </property>  
34.     </bean>  
35.       
36.     <bean id="template" class="org.springframework.orm.hibernate3.HibernateTem
plate">  
37.     <property name="sessionFactory" ref="mysessionFactory"></property>  
38.     </bean>  
39.       
40.     <bean id="d" class="com.javatpoint.EmployeeDao">  
41.     <property name="template" ref="template"></property>  
42.     </bean>  
43.       
44.       
45.     </beans>  

6) InsertTest.java

This class uses the EmployeeDao class object and calls its saveEmployee method by passing
the object of Employee class.

1. package com.javatpoint;  
2.   
3. import org.springframework.beans.factory.BeanFactory;  
4. import org.springframework.beans.factory.xml.XmlBeanFactory;  
5. import org.springframework.core.io.ClassPathResource;  
6. import org.springframework.core.io.Resource;  
7.   
8. public class InsertTest {  
9. public static void main(String[] args) {  
10.       
11.     Resource r=new ClassPathResource("applicationContext.xml");  
12.     BeanFactory factory=new XmlBeanFactory(r);  
13.       
14.     EmployeeDao dao=(EmployeeDao)factory.getBean("d");  
15.       
16.     Employee e=new Employee();  
17.     e.setId(114);  
18.     e.setName("varun");  
19.     e.setSalary(50000);  
20.       
21.     dao.saveEmployee(e);  
22.       
23. }  
24. }  

Now, if you see the table in the oracle database, record is inserted successfully.

download this example (developed using MyEclipse IDE)

Enabling automatic table creation, showing sql queries etc.


You can enable many hibernate properties like automatic table creation by hbm2ddl.auto
etc. in applicationContext.xml file. Let's see the code:

1. <property name="hibernateProperties">  
2.             <props>  
3.                 <prop key="hibernate.dialect">org.hibernate.dialect.Oracle9Dialect</pro
p>  
4.                 <prop key="hibernate.hbm2ddl.auto">update</prop>  
5.                 <prop key="hibernate.show_sql">true</prop>  
6.                   
7.             </props>  

If you write this code, you don't need to create table because table will be created
automatically.

Spring Data JPA Tutorial


Spring Data JPA API provides JpaTemplate class to integrate spring application with JPA.

JPA (Java Persistent API) is the sun specification for persisting objects in the enterprise
application. It is currently used as the replacement for complex entity beans.

The implementation of JPA specification are provided by many vendors such as:

o Hibernate
o Toplink
o iBatis
o OpenJPA etc.

Advantage of Spring JpaTemplate


You don't need to write the before and after code for persisting, updating, deleting or
searching object such as creating Persistence instance, creating EntityManagerFactory
instance, creating EntityTransaction instance, creating EntityManager instance, commiting
EntityTransaction instance and closing EntityManager.

So, it save a lot of code.

In this example, we are going to use hibernate for the implementation of JPA.

Example of Spring and JPA Integration


Let's see the simple steps to integration spring application with JPA:

1. create Account.java file


2. create Account.xml file
3. create AccountDao.java file
4. create persistence.xml file
5. create applicationContext.xml file
6. create AccountsClient.java file

In this example, we are going to integrate the hibernate application with spring. Let's see
the directory structure of jpa example with spring.

1) Account.java

It is a simple POJO class.

1. package com.javatpoint;  
2.   
3. public class Account {  
4.     private int accountNumber;  
5.     private String owner;  
6.     private double balance;  
7.         //no-arg and parameterized constructor  
8.         //getters and setters  
9. }  

2) Account.xml

This mapping file contains all the information of the persistent class.

1. <entity-mappings version="1.0"   
2.         xmlns="http://java.sun.com/xml/ns/persistence/orm"   
3.         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"   
4.         xsi:schemaLocation="http://java.sun.com/xml/ns/persistence/orm   
5.         http://java.sun.com/xml/ns/persistence/orm_1_0.xsd ">  
6.       
7.     <entity class="com.javatpoint.Account">  
8.         <table name="account100"></table>  
9.         <attributes>  
10.             <id name="accountNumber">  
11.                 <column name="accountnumber"/>  
12.             </id>  
13.             <basic name="owner">  
14.                 <column name="owner"/>  
15.             </basic>  
16.             <basic name="balance">  
17.                 <column name="balance"/>  
18.             </basic>  
19.         </attributes>  
20.     </entity>  
21. </entity-mappings>  

3) AccountDao.java

1. package com.javatpoint;  
2. import java.util.List;  
3. import org.springframework.orm.jpa.JpaTemplate;  
4. import org.springframework.transaction.annotation.Transactional;  
5. @Transactional  
6. public class AccountsDao{  
7.     JpaTemplate template;  
8.   
9.     public void setTemplate(JpaTemplate template) {  
10.         this.template = template;  
11.     }  
12.     public void createAccount(int accountNumber,String owner,double balance){  
13.         Account account = new Account(accountNumber,owner,balance);  
14.         template.persist(account);  
15.     }  
16.     public void updateBalance(int accountNumber,double newBalance){  
17.         Account account = template.find(Account.class, accountNumber);  
18.         if(account != null){  
19.             account.setBalance(newBalance);  
20.         }  
21.         template.merge(account);  
22.     }  
23.     public void deleteAccount(int accountNumber){  
24.         Account account = template.find(Account.class, accountNumber);  
25.         if(account != null)  
26.             template.remove(account);  
27.     }  
28.     public List<Account> getAllAccounts(){  
29.         List<Account> accounts =template.find("select acc from Account acc");  
30.         return accounts;  
31.     }  
32. }  

4) persistence.xml

1. <?xml version="1.0" encoding="UTF-8"?>  
2. <persistence xmlns="http://java.sun.com/xml/ns/persistence"  
3.     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
4.     xsi:schemaLocation="http://java.sun.com/xml/ns/persistence  
5.     http://java.sun.com/xml/ns/persistence/persistence_1_0.xsd" version="1.0">  
6.       
7.     <persistence-unit name="ForAccountsDB">  
8.         <mapping-file>com/javatpoint/Account.xml</mapping-file>  
9.         <class>com.javatpoint.Account</class>  
10.     </persistence-unit>  
11. </persistence>  

5) applicationContext.xml

1. <?xml version="1.0" encoding="UTF-8"?>  
2. <beans xmlns="http://www.springframework.org/schema/beans"   
3.     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"   
4.     xmlns:tx="http://www.springframework.org/schema/tx"   
5.     xsi:schemaLocation="http://www.springframework.org/schema/beans   
6.     http://www.springframework.org/schema/beans/spring-beans-3.0.xsd   
7.     http://www.springframework.org/schema/tx  
8.     http://www.springframework.org/schema/tx/spring-tx-3.0.xsd">  
9.       
10.      <tx:annotation-driven transaction-manager="jpaTxnManagerBean" proxy-
target-class="true"/>  
11.       
12.      <bean id="dataSourceBean" class="org.springframework.jdbc.datasource.Driver
ManagerDataSource">  
13.         <property name="driverClassName" value="oracle.jdbc.driver.OracleDriver">
</property>  
14.         <property name="url" value="jdbc:oracle:thin:@localhost:1521:xe"></prop
erty>  
15.         <property name="username" value="system"></property>  
16.         <property name="password" value="oracle"></property>  
17.     </bean>  
18.            
19.       <bean id="hbAdapterBean" class="org.springframework.orm.jpa.vendor.Hibern
ateJpaVendorAdapter">  
20.         <property name="showSql" value="true"></property>  
21.         <property name="generateDdl" value="true"></property>  
22.         <property name="databasePlatform" value="org.hibernate.dialect.OracleDiale
ct"></property>  
23.      </bean>  
24.       
25.     <bean id="emfBean" class="org.springframework.orm.jpa.LocalContainerEntityM
anagerFactoryBean">  
26.         <property name="dataSource" ref="dataSourceBean"></property>  
27.         <property name="jpaVendorAdapter" ref="hbAdapterBean"></property>  
28.      </bean>  
29.        
30.      <bean id="jpaTemplateBean" class="org.springframework.orm.jpa.JpaTemplate"
>  
31.         <property name="entityManagerFactory" ref="emfBean"></property>  
32.      </bean>  
33.        
34.      <bean id="accountsDaoBean" class="com.javatpoint.AccountsDao">  
35.         <property name="template" ref="jpaTemplateBean"></property>  
36.      </bean>  
37.       <bean id="jpaTxnManagerBean" class="org.springframework.orm.jpa.JpaTrans
actionManager">  
38.         <property name="entityManagerFactory" ref="emfBean"></property>  
39.     </bean>  
40.           
41. </beans>  

The generateDdl property will create the table automatically.

The showSql property will show the sql query on console.

6) Accountsclient.java

1. package com.javatpoint;  
2.   
3. import java.util.List;  
4. import org.springframework.context.ApplicationContext;  
5. import org.springframework.context.support.ClassPathXmlApplicationContext;  
6. import org.springframework.context.support.FileSystemXmlApplicationContext;  
7.   
8. public class AccountsClient{  
9. public static void main(String[] args){  
10.  ApplicationContext context = new ClassPathXmlApplicationContext("applicationCont
ext.xml");  
11.  AccountsDao accountsDao = context.getBean("accountsDaoBean",AccountsDao.clas
s);  
12.           
13.  accountsDao.createAccount(15, "Jai Kumar", 41000);  
14.  accountsDao.createAccount(20, "Rishi ", 35000);  
15.  System.out.println("Accounts created");  
16.           
17.  //accountsDao.updateBalance(20, 50000);  
18.  //System.out.println("Account balance updated");  
19.           
20.           
21.  /*List<Account> accounts = accountsDao.getAllAccounts(); 
22.  for (int i = 0; i < accounts.size(); i++) { 
23.    Account acc = accounts.get(i); 
24.    System.out.println(acc.getAccountNumber() + " : " + acc.getOwner() + " (" + acc.
getBalance() + ")"); 
25.  }*/  
26.           
27.   //accountsDao.deleteAccount(111);  
28.   //System.out.println("Account deleted");  
29.           
30.  }  
31. }  

Output
Hibernate: insert into account100 (balance, owner, accountnumber) values
(?, ?, ?)
Hibernate: insert into account100 (balance, owner, accountnumber) values
(?, ?, ?)
Accounts created

You might also like