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

Unit - IV Hibernate

Uploaded by

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

Unit - IV Hibernate

Uploaded by

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

B.Sc.

(ECS) - III

Unit - IV

Hibernate and Spring

 What is ORM?
 ORM stands for Object-Relational Mapping (ORM) is a programming technique for
converting data between relational databases and object oriented programming languages
such as Java, C# etc.
 An ORM system has following advantages over plain JDBC.
1) When we work with an object-oriented systems, there's a mismatch between the object
model and the relational database.
2) RDBMSs represent data in a tabular format whereas object-oriented languages, such as
Java or C# represent it as an interconnected graph of objects.

An ORM tool simplifies the data creation, data manipulation and data access. It is a
programming technique that maps the object to the data stored in the database.

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

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

 Introduction to Hibernate:-
 Hibernate is an Object-Relational Mapping (ORM) solution for JAVA.
 It is an open source persistent framework created by Gavin King in 2001.
 It is a powerful, high performance Object-Relational Persistence and Query service for any
Java Application.
 Hibernate is a Java framework that simplifies the development of Java application to interact
with the database.
 provides the facility to map the java classes to relational database tables and Java data types to
SQL data types.
 Note: Hibernate framework acts as an intermediate layer between java objects and
relational database.
 Hibernate is a high-performance Object/Relational persistence and query service, which is
licensed under the open source GNU Lesser General Public License (LGPL) and is free to
download.
 Object-Relational Mapping (ORM) technologies are responsible for
saving/reading/editing/deleting the objects from our application to the relational database
tables.
 ORM makes our Java application more flexible by protecting developers from working with
SQL Languages. Each relational database has its own standards of SQL language.
 Hibernate not only takes care of the mapping from Java classes to database tables (and from
Java data types to SQL data types), but also provides data query and retrieval facilities.
 It is an open source, lightweight, ORM (Object Relational Mapping) tool. Hibernate
implements the specifications of JPA (Java Persistence API) for data persistence.
 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.
 Hibernate is an Object-Relational Mapping(ORM) solution for JAVA and it raised as an open
source persistent framework created by Gavin King in 2001. It is a powerful, high
performance Object-Relational Persistence and Query service for any Java Application.
 Hibernate maps Java classes to database tables and from Java data types to SQL data types
and relieve the developer from 95% of common data persistence related programming tasks.
 Hibernate sits between traditional Java objects and database server to handle all the work in
persisting those objects based on the appropriate O/R mechanisms and patterns.
1) Hibernate takes care of mapping Java classes to database tables using XML files and
without writing any line of code.
2) Provides simple APIs for storing and retrieving Java objects directly to and from the
database.
3) If there is change in Database or in any table then the only need to change XML file
properties.
4) Abstract away the unfamiliar SQL types and provide us to work around familiar Java
Objects.
5) Hibernate does not require an application server to operate.
6) Manipulates Complex associations of objects of your database.
7) Minimize database access with smart fetching strategies.

 Advantages of Hibernate Framework :-


Following are the advantages of hibernate framework:

1) Open Source and Lightweight :-

 Hibernate framework is open source under the LGPL license and lightweight.
 Hibernate framework is available for everyone without any cost.
 The source code of Hibernate is also available on the Internet and we can also modify the
code.
2) Fast Performance :-

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

3) Database Independent Query :-

HQL (Hibernate Query Language) is the object-oriented version of SQL. It generates the
database independent queries. So you don't need to write database specific queries. Before
Hibernate, if database is changed for the project, we need to change the SQL query as well
that leads to the maintenance problem.

4) Automatic Table Creation :-

Hibernate framework provides the facility to create the tables of the database automatically.
So there is no need to create tables in the database manually.

5) Simplifies Complex Join :-

Fetching data from multiple tables is easy in hibernate framework.

6) Provides Query Statistics and Database Status :-

Hibernate supports Query cache and provide statistics about query and database status.

 Hibernate Architecture:
 The Hibernate architecture includes many objects persistent object, session factory,
transaction factory, connection factory, session, transaction etc.
 The Hibernate architecture is layered to keep you isolated from having to know the
underlying APIs. Hibernate makes use of the database and configuration data to provide
persistence services (and persistent objects) to the application.
 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:
 The detailed view of the Hibernate Application Architecture with few important core classes.
 Following is a very high level view of the Hibernate Application Architecture.
 Following is a detailed view of the Hibernate Application Architecture with its important core
classes.

Fig: Architecture of hibernate

 Hibernate framework uses many objects such as session factory, session, transaction etc.
alongwith existing Java API such as JDBC (Java Database Connectivity), JTA (Java
Transaction API) and JNDI (Java Naming Directory Interface).

Elements of Hibernate Architecture:


The elements of Hibernate architecture they are as follows:
1) Configuration Object:
2) SessionFactory Object:
3) Session Object:
4) Transaction Object:
5) Query Object:
6) Criteria Object:
1) Configuration Object:
 The Configuration object is the first Hibernate object you create in any Hibernate application
and usually created only once during application initialization.
 It represents a configuration or properties file required by the Hibernate. The Configuration
object provides two keys components:
A) Database Connection: This is handled through one or more configuration files supported by
Hibernate. These files are hibernate.properties and hibernate.cfg.xml.
B) Class Mapping Setup: This component creates the connection between the Java classes and
database tables.
 We define the properties which tell hibernate what database it has to interact with and which
JDBC driver to use.
 Hibernate uses a configuration file to get all this information.Configuration is a class which is
present in org.hibernate.cfg package.
 It activates Hibernate framework.
 The configuration object consist the configuration file used by the hibernate.
 It mainly consist the information about database connection (hibernate.cfg.xml) and class
mapping (.hbm.xml).
 It reads both configuration file and mapping files.
It activate Hibernate Framework
Configuration cfg=new Configuration();
It read both cfg file and mapping files
cfg.configure();
 It checks whether the config file is syntactically correct or not.
 If the config file is not valid then it will throw an exception. If it is valid then it creates a
meta-data in memory and returns the meta-data to object to represent the config file.

2) SessionFactory Object:
 Configuration object is used to create a SessionFactory object which inturn configures Hibernate
for the application using the supplied configuration file and allows for a Session object to be
instantiated.
 The SessionFactory is a thread safe object and used by all the threads of an application.
 The SessionFactory is heavyweight object so usually it is created during application start up and
kept for later use.
 You would need one SessionFactory object per database using a separate configuration file.
 So if you are using multiple databases then you would have to create multiple SessionFactory
objects.
 From there, it gets the JDBC properties- driver name, data source URL, username, password, etc.
Using these properties, it will create connection objects, representing connectivity to the database.
 Using these connections, a connection pool is created. All the information from the configuration
object and connection pool is used to create and return a session object.
 Hence, a session factory object is a heavyweight object. Each session factory is configured to
work with a specific database using one of the specified Hibernate dialects.
 It is immutable and thread-safe in nature.
 buildSessionFactory() method gathers the meta-data which is in the cfg Object.
 From cfg object it takes the JDBC information and create a JDBC Connection.
SessionFactory factory=cfg.buildSessionFactory();

3) Session Object:
 Session is an interface which is present in org.hibernate package.
 A Session is used to get a physical connection with a database.
 The Session object is lightweight and designed to be instantiated each time an interaction is
needed with the database. Persistent objects are saved and retrieved through a Session object.
 The session objects should not be kept open for a long time because they are not usually thread
safe and they should be created and destroyed them as needed.
 The session object is created from the SessionFactory object. It acts as a factory for Transaction,
Query and Criteria.Session object is created based upon SessionFactory object i.e. factory.
 It takes the connection object and opens a connection/session to the database, and allows the
application to perform persistence operations on the database.
 In an ORM tool, you perform all operations like INSERT, DELETE, and UPDATE using object-
oriented semantics, which means you are no longer referring to tables, rows, and columns. It is the
sessions work to do all the persistence operations for you.
 It is a light-weight object and it is not thread-safe.
 Session object is used to perform CRUD operations.
Session session=factory.buildSession();

4) Transaction Object:
 A Transaction represents a unit of work with the database and most of the RDBMS supports
transaction functionality. Transactions in Hibernate are handled by an underlying transaction
manager and transaction (from JDBC or JTA).
 This is an optional object and Hibernate applications may choose not to use this interface, instead
managing transactions in their own application code.
 Transaction object is used to give the instruction to the database to make the changes that happen
because of operation as a permanent by using commit() method.
Transaction tx=session.beginTransaction();
tx.commit();

5) Query Object:
 Query objects use SQL or Hibernate Query Language (HQL) string to retrieve data from the
database and create objects. A Query instance is used to bind query parameters, limit the number
of results returned by the query, and finally to execute the query.
 Query is an interface that present inside org.hibernate package.
 The Query object is created from Session object. It uses SQL and HQL to perform database
operations.
 A Query instance is obtained by calling Session.createQuery().
 This interface exposes some extra functionality beyond that provided by Session.iterate() and
Session.find():
1) A particular page of the result set may be selected by calling setMaxResults(),
setFirstResult().
2) Named query parameters may be used.

6)Criteria Object:
 Criteria object are used to create and execute object oriented criteria queries to retrieve objects.
 The Criteria object is created from the Session object.
 The Session is a factory for Criteria. Criterion instances are usually obtained via the factory
methods on Restrictions.

 Steps to create first Hibernate Application:


The steps to create first Hibernate Application are as follows:
1) Create the Persistent class
2) Create the mapping file for Persistent class
3) Create the Configuration file
4) Create the class that retrieves or stores the persistent object
5) Load the jar file
6) Run the first hibernate application
1) Create the Persistent class:
A simple Persistent class should follow some rules:

 A no-arg constructor: It is recommended that you have a default constructor at


least package visibility so that hibernate can create the instance of the
Persistent class by newInstance() method.
 Provide an identifier property (optional): It is mapped to the primary key column
of the database.
 Declare getter and setter methods (optional): The Hibernate recognizes the
method by getter and setter method names by default.
 Prefer non-final class: Hibernate uses the concept of proxies, that depends on
the persistent class. The application programmer will not be able to use proxies
for lazy association fetching.

The simple Persistent class:

Employee.java

public class Employee


{
private int id;
private String firstName, lastName;

public int getId()


{
return id;
}
public void setId(int id)
{
this.id = id;
}
public String getFirstName()
{
return firstName;
}
public void setFirstName(String firstName)
{
this.firstName = firstName;
}
public String getLastName()
{
return lastName;
}
}

2) Create the mapping file for Persistent class:


The mapping file name should be class_name.hbm.xml. There are many
elements of the mapping file.
 hibernate-mapping is the root element in the mapping file.
 class It is the sub-element of the hibernate-mapping element. It specifies the
Persistent class.
 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,assigned etc.
 property It is the subelement of class that specifies the property name of the Persistent
class.

The mapping file for the Employee class:

employee.hbm.xml

<?xml version='1.0' encoding='UTF-8'?>


<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">

<hibernate-mapping>
<class name="Employee" table="emp">
<id name="id">
<generator class="assigned"></generator>
</id>

<property name="firstName"></property>
<property name="lastName"></property>

</class>

</hibernate-mapping>

3) Create the Configuration file:


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

hibernate.cfg.xml
<?xml version='1.0' encoding='UTF-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-
3.0.dtd">

<hibernate-configuration>

<session-factory>

<!-- This property enables us to update the table everytime the program runs-->
<property name="hbm2ddl.auto">update</property>
<!-- We use dialect to provide information about which database we are using, we are
using mysql -->
<property name="dialect"> org.hibernate.dialect.MySQL5Dialect </property>
<property name="connection.url">jdbc:mysql://localhost:3306/SIIT</property>
<property name="connection.username">root</property>
<property name="connection.password">password</property>
<property name="connection.driver_class">com.mysql.jdbc.Driver </property>
<mapping resource="employee.hbm.xml"/>
</session-factory>

</hibernate-configuration>
4) Create the class that retrieves or stores the object:
In this class, we are simply storing the employee object to the database.

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)
{
//creating configuration object
Configuration cfg=new Configuration();
cfg.configure("hibernate.cfg.xml"); //populates the data of the configuration file
//creating seession factory object
SessionFactory factory=cfg.buildSessionFactory();
//creating session object
Session
session=factory.openSession();
//creating transaction object
Transaction t=session.beginTransaction();
Employee e1=new Employee();
e1.setId(115);
e1.setFirstName("Sachin");
e1.setLastName("Tendulkar");
session.Save(e1); //Saving the object
t.commit();//transaction is commited
session.close();
System.out.println("successfully saved");
}

 Hibernate with Annotation:


 So far you have seen how Hibernate uses XML mapping file for the transformation of data from
POJO to database tables and vice versa. Hibernate annotations are the newest way to define
mappings without the use of XML file.
 You can use annotations in addition to or as a replacement of XML mapping metadata.
 Hibernate Annotations is the powerful way to provide the metadata for the Object and Relational
Table mapping. All the metadata is clubbed into the POJO java file along with the code, this
helps the user to understand the table structure and POJO simultaneously during the
development.
 The hibernate application can be created with annotation. There are many annotations that
can be used to create hibernate application such as @Entity, @Id, @Table etc.
 Hibernate Annotations are based on the JPA 2 specification and supports all the features.
 All the JPA annotations are defined in the javax.persistence.* package. Hibernate
EntityManager implements the interfaces and life cycle defined by the JPA specification.
 The core advantage of using hibernate annotation is that you don't need to create mapping
(hbm) file. Here, hibernate annotations are used to provide the meta data.
Here are some annotations used in our POJO specifically for hibernate-

Annotations Use of annotations

@Entity Used for declaring any POJO class as an entity for a database

The @Table annotation allows you to specify the details of the table
that will be used to persist the entity in the database. some of the
attributes are-
@Table  name – override the table name
 schema
 catalogue
 enforce unique constraints

@Id Used for declaring a primary key inside our POJO class

Hibernate automatically generate the values with reference to the


@GeneratedValue
internal sequence and we don’t need to set the values manually.

The @Column annotation is used to specify the details of the


column to which a field or property will be mapped. Some
attributes are-
 Name – attribute permits the name of the column to be
@Column explicitly specified.
 length – the size of the column mostly used in strings
 unique – attribute permits the column to be marked as
containing only unique values.
 nullable – attribute permits the column to be marked NOT
NULL when the schema is generated.

@Transient Tells the hibernate, not to add this particular column

@Temporal This annotation is used to format the date for storing in the database

Used to tell hibernate that it’s a large object and is not a simple
@Lob
object

This annotation will tell hibernate to OrderBy as we do in SQL.


For example – we need to order by student firstname in ascending
@OrderBy order
@OrderBy(“firstname asc”)

These are some annotations that are mostly used in order to work with hibernate.
 Steps to create the hibernate application with Annotation:
There are 4 steps to create the hibernate application with annotation.

1) Add the jar file for oracle (if your database is oracle) and annotation
2) Create the Persistent class
3) Add mapping of Persistent class in configuration file
4) Create the class that retrieves or stores the persistent object

1) Add the jar file for oracle and annotation:

For oracle you need to add ojdbc14.jar file. For using annotation, you need to
add:

 hibernate-commons-annotations.jar
 ejb3-persistence.jar
 hibernate-
annotations.jar 2) Create the
Persistent class:

import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
@Entity
@Table(name= "emp121")
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;
}
}
Employee.java
3) Add mapping of Persistent class in configuration file:

In the hibernate.cgf.xml file, add an entry of mapping resource are as follows:

<mapping class="Employee"/>

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.MySQL5Dialect </property>
<property name="connection.url">jdbc:mysql://localhost:3306/SIIT</property>
<property name="connection.username">root</property>
<property name="connection.password">password</property>
<property name="connection.driver_class">com.mysql.jdbc.Driver </property>

<mapping class="com.javatpoint.Employee"/>
</session-factory>

</hibernate-configuration>

4) Create the class that retrieves or stores the persistent object:


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.

Test.java

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();

Employee e1=new Employee();


e1.setId(1001);
e1.setFirstName("Sachin");
e1.setLastName("Tendulkar");
Employee e2=new Employee();
e2.setId(1002);
e2.setFirstName("Amitabh");
e2.setLastName("Bacchan");

session.Save(e1);
session.Save(e2);

t.commit();
session.close();
System.out.println("successfully saved");
}
}
SQL Dialects in Hibernate:
For connecting any hibernate application with the database, you must
specify the SQL dialects. There are many Dialects classes defined for RDBMS in
the org.hibernate.dialect package. They are as follows:

RDBMS Dialect
Oracle (any version) org.hibernate.dialect.OracleDialect
Oracle9i org.hibernate.dialect.Oracle9iDialect
Oracle10g org.hibernate.dialect.Oracle10gDialect
MySQL org.hibernate.dialect.MySQLDialect
MySQL with InnoDB org.hibernate.dialect.MySQLInnoDBDialect
MySQL with org.hibernate.dialect.MySQLMyISAMDialect
MyISAM
DB2 org.hibernate.dialect.DB2Dialect
DB2 AS/400 org.hibernate.dialect.DB2400Dialect
DB2 OS390 org.hibernate.dialect.DB2390Dialect
Microsoft SQL Server org.hibernate.dialect.SQLServerDialect
Sybase org.hibernate.dialect.SybaseDialect
Sybase Anywhere org.hibernate.dialect.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
 Inheritance Mapping in Hibernate:
 We can map the inheritance hierarchy classes with the table of the
database.
Compared to JDBC we have one main advantage in hibernate, which is hibernate
inheritance. Suppose if we have base and derived classes, now if we save
derived(sub) class object, base class object will also be stored into the database. There
are three inheritance mapping strategies defined in the hibernate :

1. Table Per Hierarchy


2. Table Per Concrete class
3. Table Per Subclass

1) Table Per Hierarchy:


 Table per Hierarchy is one of the inheritance strategies in hibernate.
 In this inheritance strategy, we can map the entire hierarchy by single
table only.
 All attributes of all the classes in the hierarchy are stored in a single table.
 In a table per Hierarchy strategy :
a) Only one table is created in the database for storing data of the entire class
hierarchy.
b) Hibernate needs an additional column in the table called a discriminator column
for placing or storing the discriminator value of a subclass object.
c) The discriminator column is mandatory while it is optional in the other two
mapping strategies mentioned above.
 Here, an extra column (also known as discriminator column) is created in
the table to identify the class.

For Example:

There are three classes in this hierarchy. Employee is the super class for
Regular_Employee and Contract_Employee classes.
Now in this approach, the entire hierarchy is mapped to a single table. All attributes of all
the classes in the hierarchy are stored in a single table.
Creating Database Table to persist class Hierarchy:-
CREATE TABLE Employee1 (
id BIGINT(20) NOT NULL, name VARCHAR(50) NOT NULL,
salary INT, bouns INT, pey_per_hour INT, contract_duration INT,
discriminator VARCHAR(20) NOT NULL, PRIMARY KEY (id)
)

The Employee table will store objects of all three classes Employee, Regular_Employee and
Contract_Employee.

Table per Hierarchy using xml file:


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.
Example of Table per hierarchy using XML file:

1) Create the Persistent classes:

Employee.java:
Package mypackage;
public class Employee
{
private int id;
private String name;

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;
}

}
Regular_Employee.java:

package mypackage;

public class Regular_Employeeextends Employee


{
private float salary;
private int bonus;

public double getSalary()


{
return salary;
}

public void setSalary(double salary)


{
this.salary = salary;
}

public double getBonus()


{
return salary;
}

public void setBonus(double bonus)


{
this.bonus = bonus;
}

Contract_Employee.java
package mypackage;

public class Contract_Employeeextends Employee


{
private float pay_per_hour;
private String contract_duration;
public double getDuration()
{
return duration;
}

public void setContractDuration (double contract_duration)


{
this. contract_duration = contract_duration;
}

public double getHourlyRate()


{
return hourlyRate;
}
public void setPayPerHour (double pay_per_hour)
{
this.pay_per_hour = pay_per_hour;
}
}

2) Create the mapping file for 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="mypackage.Employee" table="Employee1" discriminator-
value="emp">
<id name="id">
<generator class="increment"></generator>
</id>
<discriminator column="type" type="string"></discriminator>
<property name="name"></property>

<subclass name="mypackage.Regular_Employee" discriminator-


value="reg_emp">
<property name="salary"></property>
<property name="bonus"></property>
</subclass>

<subclass name="mypackage.Contract_Employee" discriminator-


value="con_emp">
<property name="pay_per_hour"></property>
<property name="contract_duration"></property>
</subclass> </class> </hibernate-mapping>

3) Add mapping of hbm file in configuration 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.MySQL5Dialect </property>
<property name="connection.url">jdbc:mysql://localhost:3306/SIIT</property>
<property name="connection.username">root</property>
<property name="connection.password">password</property>
<property name="connection.driver_class">com.mysql.jdbc.Driver </property>

<mapping resource="employee.hbm.xml"/>
</session-factory>

</hibernate-configuration>

4) Create the class that stores the persistent object:


StoreData.java:

package mypackage;
import org.hibernate.*;
import org.hibernate.cfg.*;

public class StoreData {


public static void main(String[] args)
{
Session session=new
Configuration().configure("hibernate.cfg.xml").buildSessionFactory().openSession();
Transaction t=session.beginTransaction();

Employee e1=new Employee();


e1.setName("Rahul");

Regular_Employee e2=new Regular_Employee();


e2.setName("Ram"); e2.setSalary(50000);
e2.setBonus(5);

Contract_Employee e3=new Contract_Employee();


e3.setName("Shriram");
e3.setPay_per_hour(1000);
e3.setContract_duration("15 hours");

session.persist(e1);
session.persist(e2);
session.persist(e3);

t.commit();
session.close();
System.out.println("success");
}
}
}
}

Hibernate Table Per Hierarchy using Annotation:


The Annotation are as follows:

 @Inheritance(strategy=InheritanceType.SINGLE_TABLE),

 @DiscriminatorColumn and @DiscriminatorValue annotations for mapping table


per hierarchy strategy.

Example of Hibernate Table Per Hierarchy using Annotation:


The follow following steps to create simple example:

1. Create the persistent classes


2. Create the configuration file
3. Create the class to store the fetch the data

1) Create the Persistent classes


create the persistent classes representing the inheritance.

Employee.java
package mypackage;
import javax.persistence.*;

@Entity
@Table(name = "Employee1") @Inheritance(strategy=InheritanceType.SINGLE_TABLE)
@DiscriminatorColumn(name="type",discriminatorType=DiscriminatorType.STRING)
@DiscriminatorValue(value="employee")

public class Employee {


@Id
@GeneratedValue(strategy=GenerationType.AUTO)

@Column(name = "id")
private int id;

@Column(name = "name")
private String name;

//setters and getters


}

Regular_Employee.java

package mypackage;

import javax.persistence.*;

@Entity
@DiscriminatorValue("regularemployee")
public class Regular_Employee extends Employee{

@Column(name="salary")
private float salary;

@Column(name="bonus")
private int bonus;

//setters and getters


}

Contract_Employee.java

package mypackage;

import javax.persistence.Column;
import javax.persistence.DiscriminatorValue;
import javax.persistence.Entity;

@Entity
@DiscriminatorValue("contractemployee")
public class Contract_Employee extends Employee{

@Column(name="pay_per_hour")
private float pay_per_hour;
@Column(name="contract_duration")
private String contract_duration;

//setters and getters


}

2) Add the persistent classes in configuration file:

<?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>
<!-- This property enables us to update the table everytime the program runs-->
<property name="hbm2ddl.auto">update</property>
<!-- We use dialect to provide information about which database we are using, we are
using mysql -->
<property name="dialect"> org.hibernate.dialect.MySQL5Dialect </property>
<property name="connection.url">jdbc:mysql://localhost:3306/SIIT</property>
<property name="connection.username">root</property>
<property name="connection.password">password</property>
<property name="connection.driver_class">com.mysql.jdbc.Driver </property>

<mapping class="mypackage.Employee"/>
<mapping class="mypackage.Contract_Employee"/>
<mapping class="mypackage.Regular_Employee"/>
</session-factory>

</hibernate-configuration>

3) Create the class that stores the persistent object:

StoreData.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();

Employee e1=new Employee();


e1.setName("Rahul");

Regular_Employee e2=new Regular_Employee();


e2.setName("Ram"); e2.setSalary(50000);
e2.setBonus(5);

Contract_Employee e3=new Contract_Employee();


e3.setName("Shriram");
e3.setPay_per_hour(1000);
e3.setContract_duration("15 hours");

session.persist(e1);
session.persist(e2);
session.persist(e3);

t.commit();
session.close();
System.out.println("success");
}
}

2) Table Per Concrete:


 Table per Concrete Class is one of the inheritance strategies in hibernate.
 If we want to keep each concrete class object of inheritance in separate
tables of the database then we can proceed with the table per concrete
class strategy.
 In a table per Concrete Class strategy :
a) Hibernate stores each derived class object of hierarchy in a separate
table of the database.
b) The discriminator column is optional.
 In this strategy, each subclass table will have the subclass-specific
attributes and the attributes inherited from the parent class.

Creating Database Table to persist Concrete classes:


CREATE TABLE emp (
Id BIGINT(20) NOT NULL,
name VARCHAR(50) NOT NULL,
PRIMARY KEY (id)
)
CREATE TABLE regemp (
Id BIGINT(20) NOT NULL,
salary BIGINT(11) NULL,
bonus int,
PRIMARY KEY (id)
)
CREATE TABLE contemp (
Id BIGINT(20) NOT NULL,
Pey_per_hour int,
Contract_duration int,
PRIMARY KEY (id)
)

Example of Table per concrete class using xml:

1) Create the Persistent classes:

Employee.java:

package mypackage;

public class Employee


{
private int id;
private String name;

//getters and setters


}

Regular_Employee.java

package mypackage;

public class Regular_Employee extends Employee


{
private float salary;
private int bonus;

//getters and setters


}
Contract_Employee.java

package mypackage;

public class Contract_Employee extends Employee


{
private float pay_per_hour;
private String contract_duration;

//getters and setters


}
2) Create the mapping file for 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="mypackage.Employee" table="emp">
<id name="id">
<generator class="increment"></generator>
</id>

<property name="name"></property>

<union-subclass name="mypackage.Regular_Employee" table="regemp">


<property name="salary"></property>
<property name="bonus"></property>
</union-subclass>

<union-subclass name="mypackage.Contract_Employee" table="contemp">


<property name="pay_per_hour"></property>
<property name="contract_duration"></property>
</union-subclass>

</class>

</hibernate-mapping>

3) Add mapping of hbm file in configuration 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.MySQL5Dialect </property>
<property name="connection.url">jdbc:mysql://localhost:3306/SIIT</property>
<property name="connection.username">root</property>
<property name="connection.password">password</property>
<property name="connection.driver_class">com.mysql.jdbc.Driver </property>
<mapping resource="employee.hbm.xml"/>
</session-factory>

</hibernate-configuration>

4) Create the class that stores the persistent object:

StoreData.java

package com.javatpoint.mypackage;

import org.hibernate.*;
import org.hibernate.cfg.*;

public class StoreData {


public static void main(String[] args) {
Session session=new Configuration().configure("hibernate.cfg.xml")
.buildSessionFactory().openSession();

Transaction t=session.beginTransaction();

Employee e1=new Employee();


e1.setName("Rahul");

Regular_Employee e2=new Regular_Employee();


e2.setName("Ram"); e2.setSalary(50000);
e2.setBonus(5);

Contract_Employee e3=new Contract_Employee();


e3.setName("Shriram");
e3.setPay_per_hour(1000);
e3.setContract_duration("15 hours");

session.persist(e1);
session.persist(e2);
session.persist(e3);

t.commit();
session.close();
System.out.println("success");
}
}
Table Per Concrete class using Annotation:
In case of Table Per Concrete class, tables are created per class. So there are no
nullable values in the table. Disadvantage of this approach is that duplicate columns
are created in the subclass tables.

@Inheritance(strategy = InheritanceType.TABLE_PER_CLASS) annotation in


the parent class and @AttributeOverrides annotation in the subclasses.

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


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

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


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

Example of Table per concrete class using Annotation:

1) Create the Persistent classes:

Employee.java

package mypackage;
import javax.persistence.*;

@Entity
@Table(name = "emp")
@Inheritance(strategy = InheritanceType.TABLE_PER_CLASS)

public class Employee


{
@Id
@GeneratedValue(strategy=GenerationType.AUTO)

@Column(name = "id")
private int id;

@Column(name = "name")
private String name;

//setters and getters


}

Regular_Employee.java

package mypackage;
import javax.persistence.*;

@Entity @Table(name="regemp")
@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


}

Contract_Employee.java

Package mypackage;
import javax.persistence.*;
@Entity
@Table(name="contemp")
@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;
}
}

2) Add mapping of hbm file in configuration 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.MySQL5Dialect </property>
<property name="connection.url">jdbc:mysql://localhost:3306/SIIT</property>
<property name="connection.username">root</property>
<property name="connection.password">password</property>
<property name="connection.driver_class">com.mysql.jdbc.Driver </property>
<mapping class="mypackage.Employee"/>
<mapping class="mypackage.Contract_Employee"/>
<mapping class="mypackage.Regular_Employee"/>
</session-factory>
</hibernate-configuration>

3) Create the class that stores the persistent object:

package 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();

Employee e1=new Employee();


e1.setName("Rahul");

Regular_Employee e2=new Regular_Employee();


e2.setName("Ram"); e2.setSalary(50000);
e2.setBonus(5);

Contract_Employee e3=new Contract_Employee();


e3.setName("Shriram");
e3.setPay_per_hour(1000);
e3.setContract_duration("15 hours");

session.persist(e1);
session.persist(e2);
session.persist(e3);

t.commit();
session.close();
System.out.println("success");
}
}
3) Table Per Subclass:
 In Table Per Subclass, subclass tables are mapped to the Parent class table
by primary key and foreign key relationship.
 In a Table per Subclass strategy :
 For each class of hierarchy there exist a separate table in the database.
 While creating the database tables foreign key relationship is required between
the parent table and the child table.
 The discriminator column is optional.
 Since the subclass tables have a foreign key association to the superclass table,
there will not be any duplicate columns in the subclass table except one column
which is required to maintain the relation between Parent and subclass tables
through a foreign key.

 We have 3 tables emp, regemp, and contemp to persist the class data. A foreign
key relationship exists between the subclass tables and the superclass tables. Thus
the common data is stored in the emp table and subclass-specific fields are stored
in regemp and contemp tables.

Example of Table per subclass class using xml file:

1) Create the Persistent classes:

Employee.java:

package mypackage;

public class Employee


{
private int id;
private String name;

//getters and setters


}

Regular_Employee.java

package mypackage;

public class Regular_Employee extends Employee


{
private float salary;
private int bonus;

//getters and setters


}
Contract_Employee.java
package mypackage;

public class Contract_Employee extends Employee


{
private float pay_per_hour;
private String contract_duration;

//getters and setters


}
2) Create the mapping file for 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="mypackage.Employee" table="emp">
<id name="id">
<generator class="increment"></generator>
</id>

<property name="name"></property>

<joined-subclass name="mypackage.Regular_Employee" table="regemp">


<key column="id"></key>
<property name="salary"></property>
<property name="bonus"></property>
</joined-subclass>

<joined-subclass name="mypackage.Contract_Employee" table="contemp">


<key column="id"></key>
<property name="pay_per_hour"></property>
<property name="contract_duration"></property>
</joined-subclass>

</class>
</hibernate-mapping>

3) create configuration 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.MySQL5Dialect </property>
<property name="connection.url">jdbc:mysql://localhost:3306/SIIT</property>
<property name="connection.username">root</property>
<property name="connection.password">password</property>
<property name="connection.driver_class">com.mysql.jdbc.Driver </property>

<mapping class="mypackage.Employee"/>
<mapping class="mypackage.Contract_Employee"/>
<mapping class="mypackage.Regular_Employee"/>
</session-factory>
</hibernate-configuration>
4) Create the class that stores the persistent object:

StoreData.java

package com.javatpoint.mypackage;

import org.hibernate.*;
import org.hibernate.cfg.*;

public class StoreData {


public static void main(String[] args) {
Session session=new Configuration().configure("hibernate.cfg.xml")
.buildSessionFactory().openSession();

Transaction t=session.beginTransaction();

Employee e1=new Employee();


e1.setName("Shriram");

Regular_Employee e2=new Regular_Employee();


e2.setName("Rahul"); e2.setSalary(50000);
e2.setBonus(5);

Contract_Employee e3=new Contract_Employee();


e3.setName("Ram"); e3.setPay_per_hour(1000);
e3.setContract_duration("15 hours");

session.persist(e1);
session.persist(e2);
session.persist(e3);

t.commit();
session.close();
System.out.println("success");
}
}

Table Per Subclass using Annotation:


In case of table per subclass strategy, tables are created as per persistent classes but
they are reated using primary and foreign key. So there will not be duplicate columns
in the relation.
We need to specify @Inheritance(strategy=InheritanceType.JOINED) in the parent class
and @PrimaryKeyJoinColumn annotation in the subclasses.

Example of Table per subclass class using Annotation:

1) Create the Persistent classes:

Employee.java
Package mypackage;
import javax.persistence.*;

@Entity
@Table(name = "emp")
@Inheritance(strategy=InheritanceType.JOINED)

public class Employee {


@Id
@GeneratedValue(strategy=GenerationType.AUTO)

@Column(name = "id")
private int id;

@Column(name = "name")
private String name;

//setters and getters


}

Regular_Employee.java

Package mypackage;

import javax.persistence.*;

@Entity
@Table(name="regemp") @PrimaryKeyJoinColumn(name="ID")
public class Regular_Employee extends Employee{

@Column(name="salary")
private float salary;

@Column(name="bonus")
private int bonus;

//setters and getters


}

Contract_Employee.java

package mypackage;

import javax.persistence.*;

@Entity @Table(name="contemp")
@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;

//setters and getters


}

2) create configuration 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.MySQL5Dialect </property>
<property name="connection.url">jdbc:mysql://localhost:3306/SIIT</property>
<property name="connection.username">root</property>
<property name="connection.password">password</property>
<property name="connection.driver_class">com.mysql.jdbc.Driver </property>

<mapping class="mypackage.Employee"/>
<mapping class="mypackage.Contract_Employee"/>
<mapping class="mypackage.Regular_Employee"/>
</session-factory>
</hibernate-configuration>

3) Create the class that stores the persistent object:

StoreData.java

package com.javatpoint.mypackage;

import org.hibernate.*;
import org.hibernate.cfg.*;

public class StoreData {


public static void main(String[] args) {
Session session=new Configuration().configure("hibernate.cfg.xml")
.buildSessionFactory().openSession();

Transaction t=session.beginTransaction();

Employee e1=new Employee();


e1.setName("Rahul");

Regular_Employee e2=new Regular_Employee();


e2.setName("Ram"); e2.setSalary(50000);
e2.setBonus(5);
Contract_Employee e3=new Contract_Employee();
e3.setName("Shriram");
e3.setPay_per_hour(1000);
e3.setContract_duration("15 hours");

session.persist(e1);
session.persist(e2);
session.persist(e3);

t.commit();
session.close();
System.out.println("success");
}
}
 Collection Mapping in Hibernate:
We can map collection elements of Persistent class in Hibernate. You need to declare
the type of collection in Persistent class from one of the following types:

 java.util.List
 java.util.Set
 java.util.SortedSet
 java.util.Map
 java.util.SortedMap
 java.util.Collection

There are many subelements of <class> elements to map the collection.


They are <list>, <bag>, <set> and <map>

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.

Mapping List in Collection Mapping:


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

There are three subelements used in the list:

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

This is the mapping of collection if collection stores string objects. But if


collection stores entity reference (another class objects), we need to define <one- to-
many> or <many-to-many> element.

Example:
Example of mapping list in collection mapping :

1) create the Persistent class:

Question.java
package mypackage;

import java.util.List;

public class Question {


private int id;
private String qname;
private List<String> answers;

//getters and setters

2) create the Mapping file for the persistent class:

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="mypackage.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>

3) create the configuration 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.MySQL5Dialect </property>
<property name="connection.url">jdbc:mysql://localhost:3306/SIIT</property>
<property name="connection.username">root</property>
<property name="connection.password">password</property>
<property name="connection.driver_class">com.mysql.jdbc.Driver </property>

<mapping resource="question.hbm.xml"/>
</session-factory>

</hibernate-configuration>

4) Create the class to store the data

StoreData.java

package mypackage;

import java.util.ArrayList;
import org.hibernate.*;
import org.hibernate.cfg.*;

public class StoreData


{
public static void main(String[] args)
{
Session session=new Configuration().configure("hibernate.cfg.xml")
.buildSessionFactory().openSession();
Transaction t=session.beginTransaction();

ArrayList<String> list1=new ArrayList<String>();


list1.add("java is a programming language");
list1.add("java is a platform");

ArrayList<String> list2=new ArrayList<String>();


list2.add("Servlet is an Interface");
list2.add("Servlet is an API");

Question question1=new Question();


question1.setQname("What is Java?");
question1.setAnswers(list1);

Question question2=new Question();


question2.setQname("What is Servlet?");
question2.setAnswers(list2);

session.persist(question1);
session.persist(question2);

t.commit();
session.close();
System.out.println("success"); } }
How to fetch or retrieve 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 mypackage;

import java.util.*;

import org.hibernate.*;
import org.hibernate.cfg.*;

public class FetchData {


public static void main(String[] args) {

Session session=new Configuration().configure("hibernate.cfg.xml")


.buildSessionFactory().openSession();

Query query=session.createQuery("from Question");


List<Question> list=query.list();

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");

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

Example of mapping set in collection mapping.


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

Question.java

package mypackage;

import java.util.Set;
public class Question
{
private int id;
private String qname;
private Set<String> answers;

//getters and setters

2) create the Mapping file for the persistent class

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="mypackage.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>

3) create the configuration 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.MySQL5Dialect </property>
<property name="connection.url">jdbc:mysql://localhost:3306/SIIT</property>
<property name="connection.username">root</property>
<property name="connection.password">password</property>
<property name="connection.driver_class">com.mysql.jdbc.Driver </property>

<mapping resource="Question.hbm.xml"/>
</session-factory>

</hibernate-configuration>

4) Create the class to store the data

StoreData.java

package mypackage;

import java.util.ArrayList;

import org.hibernate.*;
import org.hibernate.cfg.*;

public class StoreData


{
public static void main(String[] args)
{
Session session=new Configuration().configure("hibernate.cfg.xml")
.buildSessionFactory().openSession();
Transaction t=session.beginTransaction();

HashSet<String> set1=new HashSet<String>();


set1.add("java is a programming language");
set1.add("java is a platform");

HashSet<String> set2=new HashSet<String>();


set2.add("Servlet is an Interface");
set2.add("Servlet is an API");

Question question1=new Question();


question1.setQname("What is Java?");
question1.setAnswers(set1);

Question question2=new Question();


question2.setQname("What is Servlet?");
question2.setAnswers(set2);

session.persist(question1);
session.persist(question2);

t.commit();
session.close();
System.out.println("success");
}
}

How to fetch or retrieve the data of Set


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

import java.util.*;

import org.hibernate.*;
import org.hibernate.cfg.*;

public class FetchData {


public static void main(String[] args) {

Session session=new Configuration().configure("hibernate.cfg.xml")


.buildSessionFactory().openSession();

Query query=session.createQuery("from Question");


List<Question> list=query.list();

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");

}
}

Mapping Map in Collection Mapping:


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

Example of Mapping Map in collection mapping using xml file


Create following pages for mapping map elements.

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

Question.java

package mypackage;

import java.util.Map;

public class Question {


private int id;
private String name,username;
private Map<String,String> 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

<?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="mypackage.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

<?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.Oracle10gDialect</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>

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");
}
}
How to fetch or retrieve the data of Map

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("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();
}
}
Display or retrieve Data from Database in hibernate:
Create the following steps for retrieve or display data from database
1. Create the Persistent class
2. Create the mapping file for Persistent class
3. Create the Configuration file
4. Create the class that retrieves or stores the persistent object
5. Load the jar file
6. Run the hibernate application.

1) Create the persistent class.

Student.java

public class Student


{
private int rollNumber;
private String name;
public int getRollNumber()
{
return rollNumber;
}
public void setRollNumber(int rollNumber)
{
this.rollNumber = rollNumber;
}
public String getName()
{
return name;
}
public void setName(String name)
{
this.name = name;
}
}

2) Create the mapping file for persistent class.

Student.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="Student" table="stude555">

<id name="rollNumber" column="roll_no">


<generator class="native"/>
</id>
<property name="name" column="firstname" />
</class>
</hibernate-mapping>
3) Create the configuration 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.MySQL5Dialect </property>
<property
name="connection.url">jdbc:mysql://localhost:3306/SIIT</property>
<property name="connection.username">root</property>
<property name="connection.password">password</property>
<property name="connection.driver_class">com.mysql.jdbc.Driver
</property>
<property name="show_sql">true</property>

<mapping resource="Student.hbm.xml"/>

</session-factory>

</hibernate-configuration>

4) Create the class that retrieves the persistent object:

ShowData.java

import java.util.*;
import org.hibernate.*;
import org.hibernate.cfg.*;
public class ShowData
{
public static void main(String[] args)
{
Session session=new Configuration().configure("hibernate.cfg.xml")
.buildSessionFactory().openSession();

Query query=session.createQuery("from Student");


List<Student> list=query.list();

Iterator<Student> itr=list.iterator();
while(itr.hasNext())
{
Student q=itr.next();
System.out.println(q.getRollNumber());
System.out.println(q.getName());
}
session.close();
System.out.println("success");

}
}

DELETE Data from Database in hibernate:

Create the following steps for retrieve or display data from database
1 Create the Persistent class
2 Create the mapping file for Persistent class
3 Create the Configuration file
4 Create the class that retrieves or stores the persistent object
5 Load the jar file
6 Run the hibernate application.

1) Create the persistent class.

Student.java

public class Student


{
private int rollNumber;
private String name;
public int getRollNumber()
{
return rollNumber;
}
public void setRollNumber(int rollNumber)
{
this.rollNumber = rollNumber;
}
public String getName()
{
return name;
}
public void setName(String name)
{
this.name = name;
}
}

2) Create the mapping file for persistent class.

Student.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="Student" table="stude555">
<id name="rollNumber" column="roll_no">
<generator class="native"/>
</id>
<property name="name" column="firstname" />
</class>
</hibernate-mapping>
3) Create the configuration 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.MySQL5Dialect </property>
<property
name="connection.url">jdbc:mysql://localhost:3306/SIIT</property>
<property name="connection.username">root</property>
<property name="connection.password">password</property>
<property name="connection.driver_class">com.mysql.jdbc.Driver
</property>

<property name="show_sql">true</property>

<mapping resource="Student.hbm.xml"/>

</session-factory>

</hibernate-configuration>
4) Create the class that retrieves the persistent object:

ShowData.java

import java.util.*;
import org.hibernate.*;
import org.hibernate.cfg.*;
public class ShowData
{
public static void main(String[] args)
{
Session session=new Configuration().configure("hibernate.cfg.xml")
.buildSessionFactory().openSession();

Transaction tx = session.beginTransaction();
Object obj=session.load(Student.class,new Integer(1));
Student stude=(Student)obj;

session.delete(stude);

tx.commit();
session.close();
System.out.print("delete succesfully");

}
}
}
Example to create web application using hibernate

In this example, we are going to insert the record of the user in the database.
It is simply a registration form.
index.jsp :
This page gets input from the user and sends it to the register.jsp file
using post method.

<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
It is the simple bean class representing the Persistent class in
hibernate.

package com.javatpoint.mypack;

public class User {


private int id;
private String name,password,email;

//getters and setters

}
user.hbm.xml
It maps the User class with the table of the database.

<?xml version='1.0' encoding='UTF-8'?>


<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">

<hibernate-mapping>
<class name="com.javatpoint.mypack.User" table="u400">
<id name="id">
<generator class="increment"></generator>
</id>
<property name="name"></property>
<property name="password"></property>
<property name="email"></property>
</class>

</hibernate-mapping>

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

package com.javatpoint.mypack;

import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;

public class UserDao {

public static int register(User u){


int i=0;
Session session=new Configuration().
configure().buildSessionFactory().openSession();

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.

<?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.MySQL5Dialect </property>
<property name="connection.url">jdbc:mysql://localhost:3306/SIIT</property>
<property name="connection.username">root</property>
<property name="connection.password">password</property>
<property name="connection.driver_class">com.mysql.jdbc.Driver </property>
<mapping resource="user.hbm.xml"/>
</session-factory>

</hibernate-configuration>

You might also like