Unit - IV Hibernate
Unit - IV Hibernate
(ECS) - III
Unit - IV
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.
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.
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.
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.
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.
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).
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.
Employee.java
employee.hbm.xml
<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>
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;
@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
@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
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
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:
<mapping class="Employee"/>
hibernate.cfg.xml
<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>
Test.java
import org.hibernate.*;
import org.hibernate.cfg.*;
Transaction t=session.beginTransaction();
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 :
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.
Employee.java:
Package mypackage;
public class Employee
{
private int id;
private String name;
}
Regular_Employee.java:
package mypackage;
Contract_Employee.java
package mypackage;
<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>
package mypackage;
import org.hibernate.*;
import org.hibernate.cfg.*;
session.persist(e1);
session.persist(e2);
session.persist(e3);
t.commit();
session.close();
System.out.println("success");
}
}
}
}
@Inheritance(strategy=InheritanceType.SINGLE_TABLE),
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")
@Column(name = "id")
private int id;
@Column(name = "name")
private String name;
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;
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;
<mapping class="mypackage.Employee"/>
<mapping class="mypackage.Contract_Employee"/>
<mapping class="mypackage.Regular_Employee"/>
</session-factory>
</hibernate-configuration>
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");
}
}
Employee.java:
package mypackage;
Regular_Employee.java
package mypackage;
package mypackage;
Employee.hbm.xml
<hibernate-mapping>
<class name="mypackage.Employee" table="emp">
<id name="id">
<generator class="increment"></generator>
</id>
<property name="name"></property>
</class>
</hibernate-mapping>
Hibernate.cfg.xml:
<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>
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");
}
}
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.
Employee.java
package mypackage;
import javax.persistence.*;
@Entity
@Table(name = "emp")
@Inheritance(strategy = InheritanceType.TABLE_PER_CLASS)
@Column(name = "id")
private int id;
@Column(name = "name")
private String name;
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"))
@Column(name="salary")
private float salary;
@Column(name="bonus")
private int bonus;
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"))
@Column(name="contract_duration")
private String contract_duration;
Hibernate.cfg.xml
<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>
package 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");
}
}
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.
Employee.java:
package mypackage;
Regular_Employee.java
package mypackage;
Employee.hbm.xml
<?xml version='1.0' encoding='UTF-8'?>
<!DOCTYPE hibernate-mapping PUBLIC
<hibernate-mapping>
<class name="mypackage.Employee" table="emp">
<id name="id">
<generator class="increment"></generator>
</id>
<property name="name"></property>
</class>
</hibernate-mapping>
Hibernate.cfg.xml
<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.*;
Transaction t=session.beginTransaction();
session.persist(e1);
session.persist(e2);
session.persist(e3);
t.commit();
session.close();
System.out.println("success");
}
}
Employee.java
Package mypackage;
import javax.persistence.*;
@Entity
@Table(name = "emp")
@Inheritance(strategy=InheritanceType.JOINED)
@Column(name = "id")
private int id;
@Column(name = "name")
private String name;
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;
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;
Hibernate.cfg.xml
<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>
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");
}
}
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
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.
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.
Example:
Example of mapping list in collection mapping :
Question.java
package mypackage;
import java.util.List;
Question.hbm.xml:
<hibernate-mapping>
<class name="mypackage.Question" table="q100">
<id name="id">
<generator class="increment"></generator>
</id>
<property name="qname"></property>
</class>
</hibernate-mapping>
hibernate.cfg.xml
<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>
StoreData.java
package mypackage;
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"); } }
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.*;
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.
Question.java
package mypackage;
import java.util.Set;
public class Question
{
private int id;
private String qname;
private Set<String> answers;
Question.hbm.xml
<hibernate-mapping>
<class name="mypackage.Question" table="q102">
<id name="id">
<generator class="increment"></generator>
</id>
<property name="qname"></property>
</hibernate-mapping>
hibernate.cfg.xml
<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>
StoreData.java
package mypackage;
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");
}
}
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");
}
}
Question.java
question.hbm.xml
hibernate.cfg.xml
StoreTest.java
FetchTest.java
Question.java
package mypackage;
import java.util.Map;
question.hbm.xml
<hibernate-mapping>
</hibernate-mapping>
hibernate.cfg.xml
<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();
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();
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.
Student.java
Student.hbm.xml
hibernate cfg.xml
<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>
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();
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");
}
}
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.
Student.java
Student.hbm.xml
hibernate cfg.xml
<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.
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;
}
user.hbm.xml
It maps the User class with the table of the database.
<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.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>