Hibernate PDF
Hibernate PDF
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. The
stable release of Hibernate till July 16, 2014, is hibernate 4.3.6. It is helpful for beginners and
experienced persons.
Hibernate Framework
Hibernate framework simplifies the development of java application to interact with the database.
Hibernate is an open source, lightweight, ORM (Object Relational Mapping) 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.
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 bydefault.
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.
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.
Simplifies complex join: To fetch data form multiple tables is easy in hibernate framework.
Provides query statistics and database status: Hibernate supports Query cache and provide
statistics about query and database status.
Hibernate Architecture
The Hibernate architecture includes many objects persistent object, session factory, transaction
factory, connection factory, session, transaction etc.
There are 4 layers in hibernate architecture java application layer, hibernate framework layer,
backhand api layer and 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 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).
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
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
}
id It is the subelement of class. It specifies the primary key attribute in the class.
generator It is the subelement of id. It is used to generate the primary key. There are many
generator classes such as assigned (It is used if id is specified by the user), increment, hilo,
sequence, native etc. We will learn all the generator classes later.
property It is the subelement of class that specifies the property name of the Persistent class.
employee.hbm.xml
<?xml version='1.0' encoding='UTF-8'?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate -mapping-3.0.dtd">
<hibernate-mapping>
<class name="com.javatpoint.mypackage.Employee" table="emp1000">
<id name="id">
<generator class="assigned"></generator>
</id>
<property name="firstName"></property>
<property name="lastName"></property>
</class>
</hibernate-mapping>
hibernate.cfg.xml
<?xml version='1.0' encoding='UTF-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate -configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="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">oracle</property>
<property name="connection.driver_class">oracle.jdbc.driver.OracleDriver</property>
<mapping resource="employee.hbm.xml"/>
</session-factory>
</hibernate-configuration>
package com.javatpoint.mypackage;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
Session session=factory.openSession();
t.commit();//transaction is commited
session.close();
System.out.println("successfully saved");
}
}
download the latest hibernate jar file. Some other jar files or packages are required such as
http://www.hibernate.org/downloads&hl=en-IN&tg=800&tk=p5AwbiLP8b4TOOEq
cglib
log4j
commons
SLF4J
dom4j
xalan
xerces
Note: You need to connect with the internet to run this example.
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
https://www.javatpoint.com/src/hb/hibernatejar.zip
In this example, we are connecting the application with oracle database. So you must add the
ojdbc14.jar file.
download the ojdbc14.jar file
https://www.javatpoint.com/src/jdbc/ojdbc14.jar&hl=en-IN&tg=169&tk=AOUI8Yrs5XsSptf1
Employee.java
package com.javatpoint.mypackage;
<hibernate-mapping>
<class name="com.javatpoint.mypackage.Employee" table="emp1000">
<id name="id">
<generator class="assigned"></generator>
</id>
<property name="firstName"></property>
<property name="lastName"></property>
</class>
</hibernate-mapping>
hibernate.cfg.xml
<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">oracle</property>
<property name="connection.driver_class">oracle.jdbc.driver.OracleDriver</property>
<mapping resource="employee.hbm.xml"/>
</session-factory>
</hibernate-configuration>
package com.javatpoint.mypackage;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
t.commit();//transaction is committed
session.close();
System.out.println("successfully saved");
}
}
To run the hibernate application, right click on the StoreData class - Run As - Java Application.
Note: You need to connect with the internet to run this example.
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 class because we are going to write the code to get session
object self for better understanding - finish.
Employee.java
package com.javatpoint.mypackage;
employee.hbm.xml
<?xml version='1.0' encoding='UTF-8'?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate -mapping-3.0.dtd">
<hibernate-mapping>
<class name="com.javatpoint.mypackage.Employee" table="emp1000">
<id name="id">
<generator class="assigned"></generator>
</id>
<property name="firstName"></property>
<property name="lastName"></property>
</class>
</hibernate-mapping>
<mapping resource="employee.hbm.xml"/>
hibernate.cfg.xml
<?xml version='1.0' encoding='UTF-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate -configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="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">oracle</property>
<property name="connection.driver_class">oracle.jdbc.driver.OracleDriver</property>
<mapping resource="employee.hbm.xml"/>
</session-factory>
</hibernate-configuration>
package com.javatpoint.mypackage;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
public class StoreData {
public static void main(String[] args) {
t.commit();//transaction is commited
session.close();
System.out.println("successfully saved");
}
}
To add the ojdbc14.jar file, right click on your project - build path - add external archives - select
the ojdbc14.jar file - open.
To run the hibernate application, right click on the StoreData class - Run As - Java Application.
download the hibernate example https://www.javatpoint.com/src/hb/jtfirst.zip
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.
hibernate-commons-annotations.jar
ejb3-persistence.jar
hibernate-annotations.jar
@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 bydefault.
@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 bydefault.
Employee.java
package com.javatpoint;
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;
}
}
hibernate.cfg.xml
<?xml version='1.0' encoding='UTF-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate -configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="hbm2ddl.auto">create</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">oracle</property>
<property name="connection.driver_class">oracle.jdbc.driver.OracleDriver</property>
<mapping class="com.javatpoint.Employee"/>
</session-factory>
</hibernate-configuration>
In this class, we are simply storing the employee object to the database. Here, we are using the
AnnotationConfiguration class to get the information of mapping from the persistent class.
package com.javatpoint.mypackage;
package com.javatpoint;
import org.hibernate.*;
import org.hibernate.cfg.*;
public class Test {
public static void main(String[] args) {
Session session=new AnnotationConfiguration()
.configure().buildSessionFactory().openSession();
Transaction t=session.beginTransaction();
t.commit();
session.close();
System.out.println("successfully saved");
}
}
download this hibernate example (developed using Myeclipse IDE)
https://www.javatpoint.com/src/hb/hbannotation.zip
download this hibernate example (developed using Eclipse IDE)
https://www.javatpoint.com/src/hb/eclipse/hbannotation.zip
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.
index.jsp
This page gets input from the user and sends it to the register.jsp file using post method.
<form action="register.jsp" method="post">
Name:<input type="text" name="name"/><br><br/>
Password:<input type="password" name="password"/><br><br/>
Email ID:<input type="text" name="email"/><br><br/>
<input type="submit" value="register"/>"
</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
package com.javatpoint.mypack;
user.hbm.xml
<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.Transaction;
import org.hibernate.cfg.Configuration;
Transaction t=session.beginTransaction();
t.begin();
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.
<hibernate-configuration>
<session-factory>
<property name="hbm2ddl.auto">create</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">oracle</property>
<property name="connection.driver_class">oracle.jdbc.driver.OracleDriver</property>
<mapping resource="user.hbm.xml"/>
</session-factory>
</hibernate-configuration>
download this hibernate example (developed using Myeclipse IDE)
https://www.javatpoint.com/src/hb/hbweb.zip
assigned
increment
sequence
hilo
native
identity
seqhilo
uuid
guid
select
foreign
sequence-identity
assigned
It is the default generator strategy if there is no <generator> element . In this case, application
assigns the id. For example:
<hibernate-mapping>
<class ...>
<id ...>
<generator class="assigned"></generator>
</id>
</class>
</hibernate-mapping>
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. The first generated identifier is 1 normally and incremented as 1.
Syntax:
<hibernate-mapping>
<class ...>
<id ...>
<generator class="increment"></generator>
</id>
</class>
</hibernate-mapping>
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:
<id ...>
<generator class="sequence"></generator>
</id>
For defining your own sequence, use the param subelement of generator.
<id ...>
<generator class="sequence">
<param name="sequence">your_sequence_name</param>
</generator>
</id>
4) hilo
It uses high and low algorithm to generate the id of type short, int and long. Syntax:
<id ...>
<generator class="hilo"></generator>
</id>
5) native
<id ...>
<generator class="native"></generator>
</id>
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.
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.
download the example of assigned generator
R
D
B
M
S 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.MySQLInnoDBDialect
MySQL with MyISAM org.hibernate.dialect.MySQLMyISAMDialect
D
B
2 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.SybaseAnywhereDialect
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
log4j.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE log4j:configuration SYSTEM "log4j.dtd">
<log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/"
debug="false">
<appender name="CONSOLE" class="org.apache.log4j.ConsoleAppender">
<layout class="org.apache.log4j.PatternLayout">
<param name="ConversionPattern" value="[%d{dd/MM/yy hh:mm:ss:sss z}] %5p %c{2}:
%m%n" />
</layout>
</appender>
<appender name="ASYNC" class="org.apache.log4j.AsyncAppender">
<appender-ref ref="CONSOLE" />
<appender-ref ref="FILE" />
</appender>
<appender name="FILE" class="org.apache.log4j.RollingFileAppender">
<param name="File" value="C:/javatpointlog.log" />
<param name="MaxBackupIndex" value="100" />
<layout class="org.apache.log4j.PatternLayout">
<param name="ConversionPattern" value="[%d{dd/MM/yy hh:mm:ss:sss z}] %5p %c{2}:
%m%n" />
</layout>
</appender>
<category name="org.hibernate">
<priority value="DEBUG" />
</category>
<category name="java.sql">
<priority value="debug" />
</category>
<root>
<priority value="INFO" />
<appender-ref ref="FILE" />
</root>
</log4j:configuration>
Here, we are going to enable logging using log4j through properties file.
log4j.properties
# Direct log messages to a log file
log4j.appender.file=org.apache.log4j.RollingFileAppender
log4j.appender.file.File=C:\\javatpointhibernate.log
log4j.appender.file.MaxFileSize=1MB
log4j.appender.file.MaxBackupIndex=1
log4j.appender.file.layout=org.apache.log4j.PatternLayout
log4j.appender.file.layout.ConversionPattern=%d{ABSOLUTE} %5p %c{1}:%L - %m%n
# Direct log messages to stdout
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Target=System.out
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d{ABSOLUTE} %5p %c{1}:%L - %m%n
# Root logger option
log4j.rootLogger=INFO, file, stdout
# Log everything. Good for troubleshooting
log4j.logger.org.hibernate=INFO
# Log all JDBC parameters
log4j.logger.org.hibernate.type=ALL
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 .
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
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.
<hibernate-mapping>
<class name="com.javatpoint.mypackage.Employee" table="emp121" discriminator-
value="emp">
<id name="id">
<generator class="increment"></generator>
</id>
<discriminator column="type" type="string"></discriminator>
<property name="name"></property>
<subclass name="com.javatpoint.mypackage.Regular_Employee"
discriminator-value="reg_emp">
<property name="salary"></property>
<property name="bonus"></property>
</subclass>
<subclass name="com.javatpoint.mypackage.Contract_Employee"
discriminator-value="con_emp">
<property name="pay_per_hour"></property>
<property name="contract_duration"></property>
</subclass>
</class>
</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.
File: Contract_Employee.java
package com.javatpoint.mypackage;
<hibernate-mapping>
<class name="com.javatpoint.mypackage.Employee" table="emp121" discriminator-value="emp">
<id name="id">
<generator class="increment"></generator>
</id>
<discriminator column="type" type="string"></discriminator>
<property name="name"></property>
<subclass name="com.javatpoint.mypackage.Regular_Employee" discriminator-value="reg_emp">
<property name="salary"></property>
<property name="bonus"></property>
</subclass>
<subclass name="com.javatpoint.mypackage.Contract_Employee" discriminator-value="con_emp">
<property name="pay_per_hour"></property>
<property name="contract_duration"></property>
</subclass>
</class>
</hibernate-mapping>
<mapping resource="employee.hbm.xml"/>
<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">oracle</property>
<property name="connection.driver_class">oracle.jdbc.driver.OracleDriver</property>
<mapping resource="employee.hbm.xml"/>
</session-factory>
</hibernate-configuration>
The hbm2ddl.auto property is defined for creating automatic table in the database.
package com.javatpoint.mypackage;
import org.hibernate.*;
import org.hibernate.cfg.*;
Transaction t=session.beginTransaction();
t.commit();
session.close();
System.out.println("success");
}
}
Output:
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.
There are three classes in this hierarchy. Employee is the super class for Regular_Employee and
Contract_Employee classes.
@Entity
@Table(name = "employee101")
@Inheritance(strategy=InheritanceType.SINGLE_TABLE)
@DiscriminatorColumn(name="type",discrim inatorType=DiscriminatorType.STRING)
@DiscriminatorValue(value="employee")
@Column(name = "id")
private int id;
@Column(name = "name")
private String name;
@Entity
@DiscriminatorValue("regularemployee")
public class Regular_Employee extends Employee{
@Column(name="salary")
private float salary;
@Column(name="bonus")
private int bonus;
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;
Open the hibernate.cgf.xml file, and add entries of entity classes like this:
<mapping class="com.javatpoint.mypackage.Employee"/>
<mapping class="com.javatpoint.mypackage.Contract_Employee"/>
<mapping class="com.javatpoint.mypackage.Regular_Employee"/>
</pre></div>
<table >
<tr><td>Now the configuration file will look like this:
</td></tr>
</table>
<span id="filename">File: hibernate.cfg.xml</span>
<div class="codeblock"><pre name="code" class="java" >
<?xml version='1.0' encoding='UTF-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate -configuration-3.0.dtd">
<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">oracle</property>
<property name="connection.driver_class">oracle.jdbc.driver.OracleDriver</property>
<mapping class="com.javatpoint.mypackage.Employee"/>
<mapping class="com.javatpoint.mypackage.Contract_Employee"/>
<mapping class="com.javatpoint.mypackage.Regular_Employee"/>
</session-factory>
</hibernate-configuration>
The hbm2ddl.auto property is defined for creating automatic table in the database.
File: StoreTest.java
package com.javatpoint.mypackage;
import org.hibernate.*;
import org.hibernate.cfg.*;
public class StoreData {
public static void main(String[] args) {
AnnotationConfiguration cfg=new AnnotationConfiguration();
Session session=cfg.configure("hibernate.cfg.xml").buildSessionFactory().openSession();
Transaction t=session.beginTransaction();
session.persist(e1);
session.persist(e2);
session.persist(e3);
t.commit();
session.close();
System.out.println("success");
}
}
Output:
By union-subclass element
By Self creating the table for each class
<hibernate-mapping>
<class name="com.javatpoint.mypackage.Employee" table="emp122">
<id name="id">
<generator class="increment"></generator>
</id>
<property name="name"></property>
</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:
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;
File: Regular_Employee.java
package com.javatpoint.mypackage;
package com.javatpoint.mypackage;
File: employee.hbm.xml
<hibernate-mapping>
<class name="com.javatpoint.mypackage.Employee" table="emp122">
<id name="id">
<generator class="increment"></generator>
</id>
<property name="name"></property>
</hibernate-mapping>
<mapping resource="employee.hbm.xml"/>
Now the configuration file will look like this:
File: hibernate.cfg.xml
<?xml version='1.0' encoding='UTF-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate -configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="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">oracle</property>
<property name="connection.driver_class">oracle.jdbc.driver.OracleDriver</property>
<mapping resource="employee.hbm.xml"/>
</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: StoreData.java
package com.javatpoint.mypackage;
import org.hibernate.*;
import org.hibernate.cfg.*;
t.commit();
session.close();
System.out.println("success");
}
}
download this example developed using Myeclipse IDE
https://www.javatpoint.com/src/hb/inheritance2.zip
download this example developed using Eclipse IDE
https://www.javatpoint.com/src/hb/eclipse/inheritanc e2.zip
@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.
In this example we are creating the three classes and provide mapping of these classes in the
employee.hbm.xml file.
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 = "employee102")
@Inheritance(strategy = InheritanceType.TABLE_PER_CLASS)
@Column(name = "id")
private int id;
@Column(name = "name")
private String name;
package com.javatpoint.mypackage;
import javax.persistence.*;
@Entity
@Table(name="regularemployee102")
@AttributeOverrides({
@AttributeOverride(name="id", column=@Column(name="id")),
@AttributeOverride(name="name", column=@Column(name="name"))
})
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.*;
@Entity
@Table(name="contractemployee102")
@AttributeOverrides({
@AttributeOverride(name="id", column=@Column(name="id")),
@AttributeOverride(name="name", column=@Column(name="name"))
})
public class Contract_Employee extends Employee{
@Column(name="pay_per_hour")
private float pay_per_hour;
@Column(name="contract_duration")
private String contract_duration;
public float getPay_per_hour() {
return pay_per_hour;
}
public void setPay_per_hour(float payPerHour) {
pay_per_hour = payPerHour;
}
public String getContract_duration() {
return contract_duration;
}
public void setContract_duration(String contractDuration) {
contract_duration = contractDuration;
}
}
<mapping class="com.javatpoint.mypackage.Employee"/>
<mapping class="com.javatpoint.mypackage.Contract_Employee"/>
<mapping class="com.javatpoint.mypackage.Regular_Employee"/>
</session-factory>
</hibernate-configuration>
The hbm2ddl.auto property is defined for creating automatic table in the database.
package com.javatpoint.mypackage;
import org.hibernate.*;
import org.hibernate.cfg.*;
Transaction t=session.beginTransaction();
t.commit();
session.close();
System.out.println("success");
}
}
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.
<hibernate-mapping>
<class name="com.javatpoint.mypackage.Employee" table="emp123">
<id name="id">
<generator class="increment"></generator>
</id>
<property name="name"></property>
<joined-subclass name="com.javatpoint.mypackage.Regular_Employee" table="regemp123">
<key column="eid"></key>
<property name="salary"></property>
<property name="bonus"></property>
</joined-subclass>
In case of table per subclass class, there will be three tables in the database, each representing a
particular class.
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.
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;
File: Regular_Employee.java
package com.javatpoint.mypackage;
public class Regular_Employee extends Employee{
private float salary;
private int bonus;
//getters and setters
}
File: Contract_Employee.java
package com.javatpoint.mypackage;
File: employee.hbm.xml
<hibernate-mapping>
<class name="com.javatpoint.mypackage.Employee" table="emp123">
<id name="id">
<generator class="increment"></generator>
</id>
<property name="name"></property>
<joined-subclass name="com.javatpoint.mypackage.Regular_Employee" table="regemp123">
<key column="eid"></key>
<property name="salary"></property>
<property name="bonus"></property>
</joined-subclass>
<joined-subclass name="com.javatpoint.mypackage.Contract_Employee" table="contemp123">
<key column="eid"></key>
<property name="pay_per_hour"></property>
<property name="contract_duration"></property>
</joined-subclass>
</class>
</hibernate-mapping>
Open the hibernate.cgf.xml file, and add an entry of mapping resource like this:
<mapping resource="employee.hbm.xml"/>
Now the configuration file will look like this:
File: hibernate.cfg.xml
<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">oracle</property>
<property name="connection.driver_class">oracle.jdbc.driver.OracleDriver</property>
<mapping resource="employee.hbm.xml"/>
</session-factory>
</hibernate-configuration>
The hbm2ddl.auto property is defined for creating automatic table in the database.
In this class, we are simply storing the employee objects in the database.
File: StoreData.java
package com.javatpoint.mypackage;
import org.hibernate.*;
import org.hibernate.cfg.*;
Transaction t=session.beginTransaction();
session.persist(e1);
session.persist(e2);
session.persist(e3);
t.commit();
session.close();
System.out.println("success");
}
}
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 = "employee103")
@Inheritance(strategy=InheritanceType.JOINED)
@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
@Table(name="regularemployee103")
@PrimaryKeyJoinColumn(name="ID")
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.*;
@Entity
@Table(name="contractemployee103")
@PrimaryKeyJoinColumn(name="ID")
public class Contract_Employee extends Employee{
@Column(name="pay_per_hour")
private float pay_per_hour;
@Column(name="contract_duration")
private String contract_duration;
<mapping class="com.javatpoint.mypackage.Employee"/>
<mapping class="com.javatpoint.mypackage.Contract_Employee"/>
<mapping class="com.javatpoint.mypackage.Regular_Employee"/>
File: hibernate.cfg.xml
<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">oracle</property>
<property name="connection.driver_class">oracle.jdbc.driver.OracleDriver</property>
<mapping class="com.javatpoint.mypackage.Employee"/>
<mapping class="com.javatpoint.mypackage.Contract_Employee"/>
<mapping class="com.javatpoint.mypackage.Regular_Employee"/>
</session-factory>
</hibernate-configuration>
The hbm2ddl.auto property is defined for creating automatic table in the database.
In this class, we are simply storing the employee objects in the database.
File: StoreData.java
package com.javatpoint.mypackage;
import org.hibernate.*;
import org.hibernate.cfg.*;
Transaction t=session.beginTransaction();
e2.setName("Vivek Kumar");
e2.setSalary(50000);
e2.setBonus(5);
java.util.List
java.util.Set
java.util.SortedSet
java.util.Map
java.util.SortedMap
java.util.Collection
or write the implementation of org.hibernate.usertype.UserCollectionType
The persistent class should be defined like this for collection element.
package com.javatpoint;
import java.util.List;
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:
package com.javatpoint;
import java.util.List;
package com.javatpoint;
import java.util.List;
public class Answer {
private int id;
private String answer;
private String posterName;
//getters and setters
}
<key column="qid"></key>
<index column="type"></index>
<one-to-many class="com.javatpoint.Answer" />
</list>
</class>
Here, List is mapped by one-to-many relation. In this scenario, there can be many answers for one
question.
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:
The attributes of the key element are column, on-delete, property-ref, not-null, update and unique.
<key
column="columnname"
on-delete="noaction|cascade"
not-null="true|false"
property-ref="propertyName"
update="true|false"
unique="true|false"
/>
Indexed collections
The collection elements can be categorized in two forms:
indexed ,and
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
element
component-element
one-to-many, or
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
Mapping Bag
In this example, we are going to use the bag collection of Hibernate framework.
Mapping Set
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:
package com.javatpoint;
import java.util.List;
public class Question {
private int id;
<hibernate-mapping>
<class name="com.javatpoint.Question" table="q100">
<id name="id">
<generator class="increment"></generator>
</id>
<property name="qname"></property>
<list name="answers" table="ans100">
<key column="qid"></key>
<index column="type"></index>
<element column="answer" type="string"></element>
</list>
</class>
</hibernate-mapping>
This file contains information about the database and mapping file.
<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">oracle</property>
<property name="connection.driver_class">oracle.jdbc.driver.OracleDriver</property>
<mapping resource="question.hbm.xml"/>
</session-factory>
</hibernate-configuration>
package com.javatpoint;
import java.util.ArrayList;
import org.hibernate.*;
import org.hibernate.cfg.*;
t.commit();
session.close();
System.out.println("success");
}
}
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.
package com.javatpoint;
import java.util.*;
import org.hibernate.*;
import org.hibernate.cfg.*;
Iterator<Question> itr=list.iterator();
while(itr.hasNext()){
Question q=itr.next();
System.out.println("Question Name: "+q.getQname());
//printing answers
List<String> list2=q.getAnswers();
Iterator<String> itr2=list2.iterator();
while(itr2.hasNext()){
System.out.println(itr2.next());
}
}
session.close();
System.out.println("success");
}
}
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).
package com.javatpoint;
import java.util.List;
public class Question {
private int id;
private String qname;
private List<Answer> answers;
//getters and setters
}
The Answer class has its own informations such as id, answername, postedBy etc.
package com.javatpoint;
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.
In this example, we are going to see full example of mapping list that contains entity reference.
Question.java
package com.javatpoint;
import java.util.List;
Answer.java
package com.javatpoint;
<hibernate-mapping>
<class name="com.javatpoint.Question" table="q501">
<id name="id">
<generator class="increment"></generator>
</id>
<property name="qname"></property>
<list name="answers" cascade="all">
<key column="qid"></key>
<index column="type"></index>
<one-to-many class="com.javatpoint.Answer"/>
</list>
</class>
</hibernate-mapping>
This file contains information about the database and mapping file.
<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">oracle</property>
<property name="connection.driver_class">oracle.jdbc.driver.OracleDriver</property>
<mapping resource="question.hbm.xml"/>
</session-factory>
</hibernate-configuration>
Create the class to store the data
package com.javatpoint;
import java.util.ArrayList;
import org.hibernate.*;
import org.hibernate.cfg.*;
session.persist(question1);
session.persist(question2);
t.commit();
session.close();
System.out.println("success");
}
}
OUTPUT
FetchData.java
package com.javatpoint;
import java.util.*;
import org.hibernate.*;
import org.hibernate.cfg.*;
OUTPUT
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:
</bag>
</class>
package com.javatpoint;
import java.util.List;
public class Question {
private int id;
private String qname;
private List<String> answers;
<hibernate-mapping>
<class name="com.javatpoint.Question" table="q101">
<id name="id">
<generator class="increment"></generator>
</id>
<property name="qname"></property>
<bag name="answers" table="ans101">
<key column="qid"></key>
<element column="answer" type="string"></element>
</bag>
</class>
</hibernate-mapping>
<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">oracle</property>
<property name="connection.driver_class">oracle.jdbc.driver.OracleDriver</property>
<mapping resource="question.hbm.xml"/>
</session-factory>
</hibernate-configuration>
package com.javatpoint;
import java.util.ArrayList;
import org.hibernate.*;
import org.hibernate.cfg.*;
t.commit();
session.close();
System.out.println("success");
}
}
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.
package com.javatpoint;
import java.util.*;
import org.hibernate.*;
import org.hibernate.cfg.*;
Iterator<Question> itr=list.iterator();
while(itr.hasNext()){
Question q=itr.next();
System.out.println("Question Name: "+q.getQname());
//printing answers
List<String> list2=q.getAnswers();
Iterator<String> itr2=list2.iterator();
while(itr2.hasNext()){
System.out.println(itr2.next());
}
}
session.close();
System.out.println("success");
}
}
Here, we are using the scenario of Forum where one question has multiple answers.
Let's see the persistent class that has list objects. In this case, there can be many answers for a
question and each answer may have its own informations that is why we have used list element
(containing Answer objects) to represent a collection of answers.
package com.javatpoint;
import java.util.List;
public class Question {
private int id;
private String qname;
private List<Answer> answers;
//getters and setters
}
The Answer class has its own informations such as id, answername, postedBy etc.
package com.javatpoint;
public class Answer {
private int id;
private String answername;
private String postedBy;
//getters and setters
}
}
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 bag to map this object. Let's see how we can map it.
In this example, we are going to see full example of mapping list that contains entity reference.
Question.java
package com.javatpoint;
import java.util.List;
Answer.java
package com.javatpoint;
<hibernate-mapping>
<class name="com.javatpoint.Question" table="q501">
<id name="id">
<generator class="increment"></generator>
</id>
<property name="qname"></property>
<bag name="answers" cascade="all">
<index column="type"></index>
<one-to-many class="com.javatpoint.Answer"/>
</bag>
</class>
</hibernate-mapping>
<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">oracle</property>
<property name="connection.driver_class">oracle.jdbc.driver.OracleDriver</property>
<mapping resource="question.hbm.xml"/>
</session-factory>
</hibernate-configuration>
package com.javatpoint;
import java.util.ArrayList;
import org.hibernate.*;
import org.hibernate.cfg.*;
t.commit();
session.close();
System.out.println("success");
}
}
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
package com.javatpoint;
import java.util.*;
import org.hibernate.*;
import org.hibernate.cfg.*;
Iterator<Question> itr=list.iterator();
while(itr.hasNext()){
Question q=itr.next();
System.out.println("Question Name: "+q.getQname());
//printing answers
List<Answer> list2=q.getAnswers();
Iterator<Answer> itr2=list2.iterator();
while(itr2.hasNext()){
System.out.println(itr2.next());
}
}
session.close();
System.out.println("success");
}
}
OUTPUT
Let's see how we can implement the set in the mapping file:
</class>
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.
package com.javatpoint;
import java.util.Set;
public class Question {
private int id;
private String qname;
private Set<String> answers;
<hibernate-mapping>
<class name="com.javatpoint.Question" table="q102">
<id name="id">
<generator class="increment"></generator>
</id>
<property name="qname"></property>
<set name="answers" table="ans102">
<key column="qid"></key>
<element column="answer" type="string"></element>
</set>
</class>
</hibernate-mapping>
This file contains information about the database and mapping file.
</hibernate-configuration>
package com.javatpoint;
import java.util.ArrayList;
import org.hibernate.*;
import org.hibernate.cfg.*;
t.commit();
session.close();
System.out.println("success");
}
}
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.
package com.javatpoint;
import java.util.*;
import org.hibernate.*;
import org.hibernate.cfg.*;
Iterator<Question> itr=list.iterator();
while(itr.hasNext()){
Question q=itr.next();
System.out.println("Question Name: "+q.getQname());
//printing answers
Set<String> set=q.getAnswers();
Iterator<String> itr2=set.iterator();
while(itr2.hasNext()){
System.out.println(itr2.next());
}
}
session.close();
System.out.println("success");
}
}
Let's see the persistent class that has set objects. In this case, there can be many answers for a
question and each answer may have its own informations that is why we have used set element to
represent a collection of answers.
package com.javatpoint;
import java.util.List;
The Answer class has its own informations such as id, answername, postedBy etc.
package com.javatpoint;
The Question class has set object that have entity reference (i.e. Answer class object). In such
case, we need to use one-to-many of set to map this object. Let's see how we can map it.
To understand this example, you may see the bag one-to-many relation example. We have
changed only bag to set in the hbm file and ArrayList to HashSet in the Store class.
Question.java
question.hbm.xml
hibernate.cfg.xml
StoreTest.java
FetchTest.java
Question.java
package com.javatpoint;
import java.util.Map;
public Question() {}
public Question(String name, String username, Map<String, String> answers) {
super();
this.name = name;
this.username = username;
this.answers = answers;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public Map<String, String> getAnswers() {
return answers;
}
public void setAnswers(Map<String, String> answers) {
this.answers = answers;
}
}
question.hbm.xml
<hibernate-mapping>
<class name="com.javatpoint.Question" table="question736">
<id name="id">
<generator class="native"></generator>
</id>
<property name="name"></property>
<property name="username"></property>
<map name="answers" table="answer736" cascade="all">
<key column="questionid"></key>
<index column="answer" type="string"></index>
<element column="username" type="string"></element>
</map>
</class>
</hibernate-mapping>
hibernate.cfg.xml
<mapping resource="question.hbm.xml"/>
</session-factory>
</hibernate-configuration>
StoreTest.java
package com.javatpoint;
import java.util.HashMap;
import org.hibernate.*;
import org.hibernate.cfg.*;
public class StoreTest {
public static void main(String[] args) {
Session session=new Configuration().configure().buildSessionFactory().openSession();
Transaction tx=session.beginTransaction();
HashMap<String,String> map1=new HashMap<String,String>();
map1.put("java is a programming language","John Milton");
map1.put("java is a platform","Ashok Kumar");
HashMap<String,String> map2=new HashMap<String,String>();
map2.put("servlet technology is a server side programming","John Milton");
map2.put("Servlet is an Interface","Ashok Kumar");
map2.put("Servlet is a package","Rahul Kumar");
Question question1=new Question("What is java?","Alok",map1);
Question question2=new Question("What is servlet?","Jai Dixit",map2);
session.persist(question1);
session.persist(question2);
tx.commit();
session.close();
System.out.println("successfully stored");
}
}
FetchTest.java
package com.javatpoint;
import java.util.*;
import org.hibernate.*;
import org.hibernate.cfg.*;
public class FetchTest {
public static void main(String[] args) {
Session session=new Configuration().configure().buildSessionFactory().openSession();
Iterator<Question> iterator=list.iterator();
while(iterator.hasNext()){
Question question=iterator.next();
System.out.println("question id:"+question.getId());
System.out.println("question name:"+question.getName());
System.out.println("question posted by:"+question.getUsername());
System.out.println("answers.....");
Map<String,String> map=question.getAnswers();
Set<Map.Entry<String,String>> set=map.entrySet();
Iterator<Map.Entry<String,String>> iteratoranswer=set.iterator();
while(iteratoranswer.hasNext()){
Map.Entry<String,String> entry=(Map.Entry<String,String>)iteratoranswer.next();
System.out.println("answer name:"+entry.getKey());
System.out.println("answer posted by:"+entry.getValue());
}
}
session.close();
}
}
Question.java
User.java
question.hbm.xml
user.hbm.xml
hibernate.cfg.xml
StoreTest.java
FetchTest.java
Question.java
package com.javatpoint;
import java.util.Map;
public Question() {}
public Question(String name, Map<String, User> answers) {
super();
this.name = name;
this.answers = answers;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Map<String, User> getAnswers() {
return answers;
}
public void setAnswers(Map<String, User> answers) {
this.answers = answers;
}
}
User.java
package com.javatpoint;
public User() {}
public User(String username, String email, String country) {
super();
this.username = username;
this.email = email;
this.country = country;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;K
public void setEmail(String email) {
this.email = email;
}
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
}
question.hbm.xml
<?xml version='1.0' encoding='UTF-8'?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate -mapping-3.0.dtd">
<hibernate-mapping>
<class name="com.javatpoint.Question" table="question738">
<id name="id">
<generator class="native"></generator>
</id>
<property name="name"></property>
<map name="answers" table="answer738" cascade="all">
<key column="questionid"></key>
<index column="answer" type="string"></index>
<many-to-many class="com.javatpoint.User" column="userid"></many-to-many>
</map>
</class>
</hibernate-mapping>
user.hbm.xml
<hibernate-mapping>
<class name="com.javatpoint.User" table="user738">
<id name="id">
<generator class="native"></generator>
</id>
<property name="username"></property>
<property name="email"></property>
<property name="country"></property>
</class>
</hibernate-mapping>
hibernate.cfg.xml
<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">oracle</property>
<property name="connection.driver_class">oracle.jdbc.driver.OracleDriver</property>
<mapping resource="question.hbm.xml"/>
<mapping resource="user.hbm.xml"/>
</session-factory>
</hibernate-configuration>
StoreTest.java
package com.javatpoint;
import java.util.HashMap;
import org.hibernate.*;
import org.hibernate.cfg.*;
public class StoreTest {
public static void main(String[] args) {
Session session=new Configuration().configure().buildSessionFactory().openSession();
Transaction tx=session.beginTransaction();
session.persist(question1);
session.persist(question2);
tx.commit();
session.close();
System.out.println("successfully stored");
}
}
FetchTest.java
package com.javatpoint;
import java.util.*;
import org.hibernate.*;
import org.hibernate.cfg.*;
public class FetchTest {
public static void main(String[] args) {
Session session=new Configuration().configure().buildSessionFactory().openSession();
Query query=session.createQuery("from Question ");
List<Question> list=query.list();
Iterator<Question> iterator=list.iterator();
while(iterator.hasNext()){
Question question=iterator.next();
System.out.println("question id:"+question.getId());
System.out.println("question name:"+question.getName());
System.out.println("answers.....");
Map<String,User> map=question.getAnswers();
Set<Map.Entry<String,User>> set=map.entrySet();
Iterator<Map.Entry<String,User>> iteratoranswer=set.iterator();
while(iteratoranswer.hasNext()){
Map.Entry<String,User> entry=(Map.Entry<String,User>)iteratoranswer.next();
System.out.println("answer name:"+entry.getKey());
System.out.println("answer posted by.........");
User user=entry.getValue();
System.out.println("username:"+user.getUsername());
System.out.println("user emailid:"+user.getEmail());
System.out.println("user country:"+user.getCountry());
}
}
session.close();
}
}
Bidirectional 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.
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.
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.
package com.javatpoint;
package com.javatpoint;
public class Employee {
private int id;
private String name;
private Address address;//HAS-A
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.
By many-to-one element
By one-to-one element
Here, we are going to perform one to one mapping by many-to-one element. In such case, a 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.
There are two persistent classes Employee.java and Address.java. Employee class contains
Address class reference and vice versa.
Employee.java
package com.javatpoint;
Address.java
package com.javatpoint;
employee.hbm.xml
In this mapping file we are using many-to-one element with unique="true" attribute to make the
one to one mapping.
<hibernate-mapping>
<class name="com.javatpoint.Employee" table="emp211">
<id name="employeeId">
<generator class="increment"></generator>
</id>
<property name="name"></property>
<property name="email"></property>
<many-to-one name="address" unique="true" cascade="all"></many-to-one>
</class>
</hibernate-mapping>
address.hbm.xml
This is the simple mapping file for the Address class.
<hibernate-mapping>
<class name="com.javatpoint.Address" table="address211">
<id name="addressId">
<generator class="increment"></generator>
</id>
<property name="addressLine1"></property>
<property name="city"></property>
<property name="state"></property>
<property name="country"></property>
</class>
</hibernate-mapping>
3) Configuration file
This file contains information about the database and mapping file.
hibernate.cfg.xml
<?xml version='1.0' encoding='UTF-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate -configuration-3.0.dtd">
<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">oracle</property>
<property name="connection.driver_class">oracle.jdbc.driver.OracleDriver</property>
<mapping resource="employee.hbm.xml"/>
<mapping resource="address.hbm.xml"/>
</session-factory>
</hibernate-configuration>
package com.javatpoint;
import org.hibernate.cfg.*;
import org.hibernate.*;
e1.setAddress(address1);
address1.setEmployee(e1);
session.persist(e1);
tx.commit();
session.close();
System.out.println("success");
}
}
Fetch.java
package com.javatpoint;
import java.util.Iterator;
import java.util.List;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
session.close();
System.out.println("success");
}
}
In hibernate framework, we have Transaction interface that defines the unit of work. It maintains
abstraction from the transaction implementation (JTA,JDBC).
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.
try {
session = sessionFactory.openSession();
tx = session.beginTransaction();
//some action
8.
tx.commit();
Advantage of HQL
database independent
supports polymorphic queries
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:
You may call avg(), min(), max() etc. aggregate functions by HQL. Let's see some common
examples:
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.
Restrictions class
Restrictions class provides methods that can be used as Criterion. The commonly used methods
of Restrictions class are as follows:
public static SimpleExpression lt(String propertyName,Object value) sets the less than
constraint to the given property.
public static SimpleExpression le(String propertyName,Object value) sets the less than or
equal constraint to the given property.
public static SimpleExpression gt(String propertyName,Object value) sets the greater than
constraint to the given property.
public static SimpleExpression ge(String propertyName,Object value) sets the greater
than or equal than constraint to the given property.
public static SimpleExpression ne(String propertyName,Object value) sets the not equal
constraint to the given property.
public static SimpleExpression eq(String propertyName,Object value) sets the equal
constraint to the given property.
public static Criterion between(String propertyName, Object low, Object high) sets the
between constraint.
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:
public static Order asc(String propertyName) applies the ascending order on the basis of
given property.
public static Order desc(String propertyName) applies the descending order on the basis of
given property.
Example of HCQL to get the records whose salary is greater than 10000
Crietria c=session.createCriteria(Emp.class);
c.add(Restrictions.gt("salary",10000));//salary is the propertyname
List list=c.list();
Crietria c=session.createCriteria(Emp.class);
c.addOrder(Order.asc("salary"));
List list=c.list();
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.
Criteria c=session.createCriteria(Emp.class);
c.setProjection(Projections.property("name"));
List list=c.list();
@NamedQueries(
{
@NamedQuery(
name = "findEmployeeByName",
query = "from Employee e where e.name = :name"
)
}
)
In this example, we are using annotations to defined the named query in the persistent class. There
are three files only:
Employee.java
hibernate.cfg.xml
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.
package com.javatpoint;
import javax.persistence.*;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
@NamedQueries(
{
@NamedQuery(
name = "findEmployeeByName",
query = "from Employee e where e.name = :name"
)
}
)
@Entity
@Table(name="em")
public class Employee {
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.
<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">oracle</property>
<property name="connection.driver_class">oracle.jdbc.driver.OracleDriver</property>
<mapping class="com.javatpoint.Employee"/>
</session-factory>
</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.
package com.javatpoint;
import java.util.Iterator;
import java.util.List;
import org.hibernate.cfg.AnnotationConfiguration;
import org.hibernate.*;
public class FetchData {
public static void main(String[] args) {
Iterator<Employee> itr=employees.iterator();
while(itr.hasNext()){
Employee e=itr.next();
System.out.println(e);
}
session.close();
}
}
download this hibernate example (developed using Myeclipse IDE)
https://www.javatpoint.com/src/hb/namedquery.zip
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
<?xml version='1.0' encoding='UTF-8'?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate -mapping-3.0.dtd">
<hibernate-mapping>
<class name="com.javatpoint.Employee" table="em">
<id name="id">
<generator class="native"></generator>
</id>
<property name="name"></property>
<property name="job"></property>
<property name="salary"></property>
</class>
<query name="findEmployeeByName">
<![CDATA[from Employee e where e.name = :name]]>
</query>
</hibernate-mapping>
Employee.java
package com.javatpoint;
public class Employee {
int id;
String name;
int salary;
String job;
//getters and setters
}
hibernate.cfg.xml
<mapping resource="emp.hbm.xml"/>
There are mainly two types of caching: first level cache and second 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 implementations are provided by different vendors such as:
SessionFactory holds the second level cache data. It is global for all the session objects and not
enabled by default.
EH Cache
OS Cache
Swarm Cache
JBoss Cache
Each implementation provides different cache usage functionality. There are four ways to use
second level cache.
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:
Let's see the second level cache implementation and cache usage.
Implementation read-only nonstrict-read-write read-write transactional
EH Cache Yes Yes Yes No
1. <property
name="cache.provider_class">org.hibernate.cache.EhCacheProvider</property>
2. <property name="hibernate.cache.use_second_level_cache">true</property>
<?xml version="1.0"?>
<ehcache>
<defaultCache
maxElementsInMemory="100"
eternal="true"/>
</ehcache>
To understand the second level cache through example, we need to create following pages:
Employee.java
employee.hbm.xml
hibernate.cfg.xml
ehcache.xml
FetchTest.java
Here, we are assuming, there is emp1012 table in the oracle database containing some records.
File: Employee.java
package com.javatpoint;
public class Employee {
private int id;
private String name;
private float salary;
public Employee() {}
public Employee(String name, float salary) {
super();
this.name = name;
this.salary = salary;
}
//setters and getters
}
File: employee.hbm.xml
<hibernate-mapping>
<class name="com.javatpoint.Employee" table="emp1012">
<cache usage="read-only" />
<id name="id">
<generator class="native"></generator>
</id>
<property name="name"></property>
<property name="salary"></property>
</class>
</hibernate-mapping>
Here, we are using read-only cache usage for the class. The cache usage can also be used in
collection.
File: hibernate.cfg.xml
<property name="cache.provider_class">org.hibernate.cache.EhCacheProvider</property>
<property name="hibernate.cache.use_second_level_cache">true</property>
<mapping resource="employee.hbm.xml"/>
</session-factory>
</hibernate-configuration>
File: ehcache.xml
<?xml version="1.0"?>
<ehcache>
<defaultCache
maxElementsInMemory="100"
eternal="false"
timeToIdleSeconds="120"
timeToLiveSeconds="200" />
<cache name="com.javatpoint.Employee"
maxElementsInMemory="100"
eternal="false"
timeToIdleSeconds="5"
timeToLiveSeconds="200" />
</ehcache>
defaultCache will be used for all the persistent classes. We can also define persistent class
explicitely by using the cache element.
timeToIdleSeconds It defines that how many seconds object can be idle in the second level
cache.
timeToLiveSeconds It defines that how many seconds object can be stored in the second level
cache whether it is idle or not.
File: FetchTest.java
package com.javatpoint;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
Session session1=factory.openSession();
Employee emp1=(Employee)session1.load(Employee.class,121);
System.out.println(emp1.getId()+" "+emp1.getName()+" "+emp1.getSalary());
session1.close();
Session session2=factory.openSession();
Employee emp2=(Employee)session2.load(Employee.class,121);
System.out.println(emp2.getId()+" "+emp2.getName()+" "+emp2.getSalary());
session2.close();
}
}
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.
In this example, we going to use struts 2 framework with hibernate. You need to have jar files for
struts 2 and hibernate.
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.
index.jsp
In this page, we have created a form using the struts tags. The action name for this form is register.
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.
package com.javatpoint;
public class User {
private int id;
private String name;
//getters and setters
RegisterDao.java
It is a java class that saves the object of User class using the Hibernate framework.
package com.javatpoint;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
Transaction t=session.beginTransaction();
int i=(Integer)session.save(u);
t.commit();
session.close();
return i;
}
}
user.hbm.xml
This mapping file contains all the information of the persitent class.
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.
<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">oracle</property>
<property name="connection.driver_class">oracle.jdbc.driver.OracleDriver</property>
<mapping resource="user.hbm.xml"/>
</session-factory>
</hibernate-configuration>
struts.xml
This files contains information about the action class to be invoked. Here the action class is User.
It is the welcome file, that displays the welcome message with username.
web.xml
It is web.xml file that contains the information about the controller. In case of Struts2,
StrutsPrepareAndExecuteFilter class works as the controller.
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5"
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema -instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
<filter>
<filter-name>struts2</filter-name>
<filter-class>
org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter
</filter-class>
</filter>
<filter-mapping>
<filter-name>struts2</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
</web-app>
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.
//creating configuration
Configuration cfg=new Configuration();
cfg.configure("hibernate.cfg.xml");
//creating seession factory object
SessionFactory factory=cfg.buildSessionFactory();
As you can see in the code of sole hibernate, you have to follow so many steps.
Now, you don't need to follow so many steps. You can simply write this:
2) Serializable save(Object entity) persists the given object and returns id.
persists or updates the given object. If id is found, it
3) void saveOrUpdate(Object entity) updates the record otherwise saves the
record.
Steps
Let's see what are the simple steps for hibernate and spring integration:
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
It is a simple POJO class. Here it works as the persistent class for hibernate.
package com.javatpoint;
This mapping file contains all the information of the persistent class.
<hibernate-mapping>
<class name="com.javatpoint.Employee" table="emp558">
<id name="id">
<generator class="assigned"></generator>
</id>
<property name="name"></property>
<property name="salary"></property>
</class>
</hibernate-mapping>
EmployeeDao.java
It is a java class that uses the HibernateTemplate class method to persist the object of Employee
class.
package com.javatpoint;
import org.springframework.orm.hibernate3.HibernateTemplate;
import java.util.*;
public class EmployeeDao {
HibernateTemplate template;
public void setTemplate(HibernateTemplate template) {
this.template = template;
}
//method to save employee
public void saveEmployee(Employee e){
template.save(e);
}
//method to update employee
public void updateEmployee(Employee e){
template.update(e);
}
//method to delete employee
public void deleteEmployee(Employee e){
template.delete(e);
}
//method to return one employee of given id
public Employee getById(int id){
Employee e=(Employee)template.get(Employee.class,id);
return e;
}
//method to return all employees
public List<Employee> getEmployees(){
List<Employee> list=new ArrayList<Employee>();
list=template.loadAll(Employee.class);
return list;
}
}
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
.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource"></property>
<property name="mappingResources">
<list>
<value>employee.hbm.xml</value>
</list>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.Oracle9Dialect</prop>
<prop key="hibernate.hbm2ddl.auto">update</prop>
<prop key="hibernate.show_sql">true</prop>
</props>
</property>
</bean>
<bean id="template" class="org.springframework.orm.hibernate3.HibernateTemplate">
<property name="sessionFactory" ref="mysessionFactory"></property>
</bean>
<bean id="d" class="com.javatpoint.EmployeeDao">
<property name="template" ref="template"></property>
</bean>
</beans>
InsertTest.java
This class uses the EmployeeDao class object and calls its saveEmployee method by passing the
object of Employee class.
package com.javatpoint;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
EmployeeDao dao=(EmployeeDao)factory.getBean("d");
}
}
Now, if you see the table in the oracle database, record is inserted successfully.
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.Oracle9Dialect</prop>
<prop key="hibernate.hbm2ddl.auto">update</prop>
<prop key="hibernate.show_sql">true</prop>
</props>
If you write this code, you don't need to create table because table will be created automatically.
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.
package com.javatpoint;
package com.javatpoint;
public class Employee {
private int id;
private String name;
private Address address;//HAS-A
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.
by annotation
by mapping file.
If you want to use named query in hibernate, you need to have knowledge of @NamedQueries
and @NamedQuery annotations.
@NamedQueries(
{
@NamedQuery(
name = "findEmployeeByName",
query = "from Employee e where e.name = :name"
)
}
)
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.
package com.javatpoint;
import javax.persistence.*;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
@NamedQueries(
{
@NamedQuery(
name = "findEmployeeByName",
query = "from Employee e where e.name = :name"
)
}
)
@Entity
@Table(name="em")
public class Employee {
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.
<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">oracle</property>
<property name="connection.driver_class">oracle.jdbc.driver.OracleDriver</property>
<mapping class="com.javatpoint.Employee"/>
</session-factory>
</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.
package com.javatpoint;
import java.util.Iterator;
import java.util.List;
import org.hibernate.cfg.AnnotationConfiguration;
import org.hibernate.*;
Iterator<Employee> itr=employees.iterator();
while(itr.hasNext()){
Employee e=itr.next();
System.out.println(e);
}
session.close();
}
}
download this hibernate example (developed using Myeclipse IDE)
https://www.javatpoint.com/src/hb/namedquery.zip
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.
emp.hbm.xml
<?xml version='1.0' encoding='UTF-8'?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate -mapping-3.0.dtd">
<hibernate-mapping>
<class name="com.javatpoint.Employee" table="em">
<id name="id">
<generator class="native"></generator>
</id>
<property name="name"></property>
<property name="job"></property>
<property name="salary"></property>
</class>
<query name="findEmployeeByName">
<![CDATA[from Employee e where e.name = :name]]>
</query>
</hibernate-mapping>
Employee.java
package com.javatpoint;
public class Employee {
int id;
String name;
int salary;
String job;
//getters and setters
}
Now include the mapping resource in the hbm file as:
hibernate.cfg.xml
<mapping resource="emp.hbm.xml"/>
download this hibernate example (developed using Myeclipse IDE)
https://www.javatpoint.com/src/hb/namedquerymapping.zip
Caching in Hibernate
Hibernate caching improves the performance of the application by pooling the object in the cache.
There are mainly two types of caching: first level cache and second level cache.
Second Level Cache implementations are provided by different vendors such as:
SessionFactory holds the second level cache data. It is global for all the session objects and not
enabled by default.
EH Cache
OS Cache
Swarm Cache
JBoss Cache
Each implementation provides different cache usage functionality. There are four ways to use
second level cache.
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:
Let's see the second level cache implementation and cache usage.
Implementation read-only nonstrict-read-write read-write transactional
EH Cache Yes Yes Yes No
1. <property
name="cache.provider_class">org.hibernate.cache.EhCacheProvider</property>
2. <property name="hibernate.cache.use_second_level_cache">true</property>
<?xml version="1.0"?>
<ehcache>
<defaultCache
maxElementsInMemory="100"
eternal="true"/>
</ehcache>
Employee.java
employee.hbm.xml
hibernate.cfg.xml
ehcache.xml
FetchTest.java
Here, we are assuming, there is emp1012 table in the oracle database containing some records.
File: Employee.java
package com.javatpoint;
File: employee.hbm.xml
<hibernate-mapping>
<class name="com.javatpoint.Employee" table="emp1012">
<cache usage="read-only" />
<id name="id">
<generator class="native"></generator>
</id>
<property name="name"></property>
<property name="salary"></property>
</class>
</hibernate-mapping>
Here, we are using read-only cache usage for the class. The cache usage can also be used in
collection.
File: hibernate.cfg.xml
<?xml version='1.0' encoding='UTF-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate -configuration-3.0.dtd">
<!-- Generated by MyEclipse Hibernate Tools. -->
<hibernate-configuration>
<session-factory>
<property name="show_sql">true</property>
<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">oracle</property>
<property name="connection.driver_class">oracle.jdbc.driver.OracleDriver</property>
<property name="cache.provider_class">org.hibernate.cache.EhCacheProvider</property>
<property name="hibernate.cache.use_second_level_cache">true</property>
<mapping resource="employee.hbm.xml"/>
</session-factory>
</hibernate-configuration>
File: ehcache.xml
<?xml version="1.0"?>
<ehcache>
<defaultCache
maxElementsInMemory="100"
eternal="false"
timeToIdleSeconds="120"
timeToLiveSeconds="200" />
<cache name="com.javatpoint.Employee"
maxElementsInMemory="100"
eternal="false"
timeToIdleSeconds="5"
timeToLiveSeconds="200" />
</ehcache>
timeToIdleSeconds It defines that how many seconds object can be idle in the second level
cache.
timeToLiveSeconds It defines that how many seconds object can be stored in the second level
cache whether it is idle or not.
File: FetchTest.java
package com.javatpoint;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
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.
In this example, we going to use struts 2 framework with hibernate. You need to have jar files for
struts 2 and hibernate.
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.
index.jsp
In this page, we have created a form using the struts tags. The action name for this form is register.
</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.
package com.javatpoint;
public class User {
private int id;
private String name;
//getters and setters
RegisterDao.java
It is a java class that saves the object of User class using the Hibernate framework.
package com.javatpoint;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
Transaction t=session.beginTransaction();
int i=(Integer)session.save(u);
t.commit();
session.close();
return i;
}
}
user.hbm.xml
This mapping file contains all the information of the persitent class.
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.
<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">oracle</property>
<property name="connection.driver_class">oracle.jdbc.driver.OracleDriver</property>
<mapping resource="user.hbm.xml"/>
</session-factory>
</hibernate-configuration>
struts.xml
This files contains information about the action class to be invoked. Here the action class is User.
welcome.jsp
It is the welcome file, that displays the welcome message with username.
web.xml
It is web.xml file that contains the information about the controller. In case of Struts2,
StrutsPrepareAndExecuteFilter class works as the controller.
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.
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.
//creating configuration
Configuration cfg=new Configuration();
cfg.configure("hibernate.cfg.xml");
t.commit();//transaction is commited
session.close();
As you can see in the code of sole hibernate, you have to follow so many steps.
Now, you don't need to follow so many steps. You can simply write this:
2) Serializable save(Object entity) persists the given object and returns id.
persists or updates the given object. If id is
found, it updates the record otherwise saves
the
3) void saveOrUpdate(Object entity)
record.
Steps
Let's see what are the simple steps for hibernate and spring integration:
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
It is a simple POJO class. Here it works as the persistent class for hibernate.
package com.javatpoint;
}
employee.hbm.xml
This mapping file contains all the information of the persistent class.
<hibernate-mapping>
<class name="com.javatpoint.Employee" table="emp558">
<id name="id">
<generator class="assigned"></generator>
</id>
<property name="name"></property>
<property name="salary"></property>
</class>
</hibernate-mapping>
EmployeeDao.java
It is a java class that uses the HibernateTemplate class method to persist the object of Employee
class.
package com.javatpoint;
import org.springframework.orm.hibernate3.HibernateTemplate;
import java.util.*;
public class EmployeeDao {
HibernateTemplate template;
public void setTemplate(HibernateTemplate template) {
this.template = template;
}
//method to save employee
public void saveEmployee(Employee e){
template.save(e);
}
//method to update employee
public void updateEmployee(Employee e){
template.update(e);
}
//method to delete employee
public void deleteEmployee(Employee e){
template.delete(e);
}
//method to return one employee of given id
public Employee getById(int id){
Employee e=(Employee)template.get(Employee.class,id);
return e;
}
//method to return all employees
public List<Employee> getEmployees(){
List<Employee> list=new ArrayList<Employee>();
list=template.loadAll(Employee.class);
return list;
}
}
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
InsertTest.java
This class uses the EmployeeDao class object and calls its saveEmployee method by passing the
object of Employee class.
package com.javatpoint;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
public class InsertTest {
public static void main(String[] args) {
EmployeeDao dao=(EmployeeDao)factory.getBean("d");
Now, if you see the table in the oracle database, record is inserted successfully.
download this example (developed using MyEclipse IDE)
https://www.javatpoint.com/src/hb/sphbinteg.zip
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.Oracle9Dialect</prop>
<prop key="hibernate.hbm2ddl.auto">update</prop>
<prop key="hibernate.show_sql">true</prop>
</props>
If you write this code, you don't need to create table because table will be created automatically.
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.
package com.javatpoint;
package com.javatpoint;
public class Employee {
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.
<class name="com.javatpoint.Employee" table="emp177">
<id name="id">
<generator class="increment"></generator>
</id>
<property name="name"></property>
<component name="address" class="com.javatpoint.Address">
<property name="city"></property>
<property name="country"></property>
<property name="pincode"></property>
</component>
</class>