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

Hibernate

Hibernate is an ORM framework that simplifies interaction between Java objects and a database. It maps Java objects to database tables and allows developers to interact with the database using Java objects rather than SQL queries. Hibernate provides features like caching, lazy loading, automatic table creation and more to simplify data access. Developers configure Hibernate using XML mapping files or annotations to define how Java objects map to database tables.
Copyright
© © All Rights Reserved
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
254 views

Hibernate

Hibernate is an ORM framework that simplifies interaction between Java objects and a database. It maps Java objects to database tables and allows developers to interact with the database using Java objects rather than SQL queries. Hibernate provides features like caching, lazy loading, automatic table creation and more to simplify data access. Developers configure Hibernate using XML mapping files or annotations to define how Java objects map to database tables.
Copyright
© © All Rights Reserved
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 17

1) Hibernate Framework

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

2) ORM Tool
------------
An ORM tool simplifies the data creation, data manipulation and data access. It is
a programming technique that maps the object to the data stored in the database.
The ORM tool internally uses the JDBC API to interact with the database.

Java application ------ Object -------- ORM tool ----- Database

3) Advantages of Hibernate Framework


-------------------------------------

Following are the advantages of hibernate framework:

1) Open Source and Lightweight


Hibernate framework is open source under the LGPL license and lightweight.

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

3) Database Independent Query


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

4) Automatic Table Creation


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

5) Simplifies Complex Join


Fetching data from multiple tables is easy in hibernate framework.

6) Provides Query Statistics and Database Status


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

4) Elements of Hibernate Architecture


--------------------------------------
For creating the first hibernate application, we must know the elements of
Hibernate architecture. They are as follows:

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

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

Transaction
The transaction object specifies the atomic unit of work. It is optional. The
org.hibernate.Transaction interface provides methods for transaction management.

ConnectionProvider
It is a factory of JDBC connections. It abstracts the application from
DriverManager or DataSource. It is optional.

TransactionFactory
It is a factory of Transaction. It is optional

5) Hibernate Example using XML in Eclipse


--------------------------------------------
Create the java project
Add jar files for hibernate
Create the Persistent class
Create the mapping file for Persistent class
Create the Configuration file
Create the class that retrieves or stores the persistent object
Run the application

3) Create the Persistent class


package com.javatpoint.mypackage;

public class Employee {


private int id;
private String firstName,lastName;
//setters and getters

4) 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 5.3//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-5.3.dtd">

<hibernate-mapping>
<class name="com.javatpoint.mypackage.Employee" table="emp1000">
<id name="id">
<generator class="assigned"></generator>
</id>

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

</class>

</hibernate-mapping>
5) Create the Configuration file

hibernate.cfg.xml

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


<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 5.3//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-5.3.dtd">

<hibernate-configuration>

<session-factory>
<property name="hbm2ddl.auto">update</property>
<property name="dialect">org.hibernate.dialect.Oracle9Dialect</property>
<property
name="connection.url">jdbc:oracle:thin:@localhost:1521:xe</property>
<property name="connection.username">system</property>
<property name="connection.password">oracle</property>
<property
name="connection.driver_class">oracle.jdbc.driver.OracleDriver</property>
<mapping resource="employee.hbm.xml"/>
</session-factory>

</hibernate-configuration>

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


package com.javatpoint.mypackage;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.boot.Metadata;
import org.hibernate.boot.MetadataSources;
import org.hibernate.boot.registry.StandardServiceRegistry;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;

public class StoreData {

public static void main( String[] args )


{
StandardServiceRegistry ssr = new
StandardServiceRegistryBuilder().configure("hibernate.cfg.xml").build();
Metadata meta = new MetadataSources(ssr).getMetadataBuilder().build();

SessionFactory factory = meta.getSessionFactoryBuilder().build();


Session session = factory.openSession();
Transaction t = session.beginTransaction();

Employee e1=new Employee();


e1.setId(1);
e1.setFirstName("Gaurav");
e1.setLastName("Chawla");

session.save(e1);
t.commit();
System.out.println("successfully saved");
factory.close();
session.close();
}
}

6) Hibernate Example using Annotation in Eclipse


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

Hibernate Annotations are based on the JPA 2 specification and supports all the
features.

All the JPA annotations are defined in the javax.persistence package. Hibernate
EntityManager implements the interfaces and life cycle defined by the JPA
specification.
The core advantage of using hibernate annotation is that you don't need to create
mapping (hbm) file. Here, hibernate annotations are used to provide the meta data.

Create new maven project


Add hibernate dependencies in pom.xml file
Create Entity class using @Entity, @Table, @Id, @Column etc annotations.
Create a hibernate configuration file
Create a class to perform DB operation using hiberanate

hibernate.cfg.xml
------------------

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


<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 5.3//EN"
"http://www.hibernate.org/dtd/hibernate-configuration-5.3.dtd">
<hibernate-configuration>
<session-factory>

<property name="hbm2ddl.auto">update</property>
<property name="dialect">org.hibernate.dialect.Oracle9Dialect</property>

<property
name="connection.url">jdbc:oracle:thin:@localhost:1521:xe</property>
<property name="connection.username">system</property>
<property name="connection.password">jtp</property>
<property
name="connection.driver_class">oracle.jdbc.driver.OracleDriver</property>

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

7) Generator classes in Hibernate


----------------------------------
The <generator> class is a sub-element of id. It is used to generate the unique
identifier for the objects of persistent class.
There are many generator classes defined in the Hibernate Framework.

All the generator classes implements the org.hibernate.id.IdentifierGenerator


interface. The application programmer may create one's own generator classes by
implementing the IdentifierGenerator interface. Hibernate framework provides many
built-in generator classes:

assigned
increment
sequence
hilo
native
identity
seqhilo
uuid
guid
select
foreign
sequence-identity

1) assigned

It is the default generator strategy if there is no <generator> element. In this


case, application assigns the id.

For example:
....
<hibernate-mapping>
<class ...>
<id ...>
<generator class="assigned"></generator>
</id>

.....

</class>
</hibernate-mapping>

3) sequence

For defining your own sequence, use the param subelement of generator.

.....
<id ...>
<generator class="sequence">
<param name="sequence">your_sequence_name</param>
</generator>
</id>
.....

8) SQL Dialects in Hibernate


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

Syntax of SQL Dialect


<property name="dialect">org.hibernate.dialect.Oracle9Dialect</property>

List of SQL Dialects


There are many Dialects classes defined for RDBMS in the org.hibernate.dialect
package. They are as follows:
RDBMS Dialect
Oracle org.hibernate.dialect.OracleDialect
MySQL org.hibernate.dialect.MySQLDialect

9) Hibernate Logging by Log4j using xml file


----------------------------------------------

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

There are two ways to perform logging using log4j:

By log4j.xml file (or)


By log4j.properties file

10) Levels of Logging


--------------------------
Following are the common logging levels.

Levels Description
OFF This level is used to turn off logging.
WARNING This is a message level that indicates a problem.
SEVERE This is a message level that indicates a failure.
INFO This level is used for informational messages.
CONFIG This level is used for static configuration messages.

11) Steps to perform Hibernate Logging by Log4j using xml file


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

Load the log4j jar files with hibernate


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

log4j.properties
# Direct log messages to a log file
log4j.appender.file=org.apache.log4j.RollingFileAppender
log4j.appender.file.File=C:\\javatpointhibernate.log
log4j.appender.file.MaxFileSize=1MB
log4j.appender.file.MaxBackupIndex=1
log4j.appender.file.layout=org.apache.log4j.PatternLayout
log4j.appender.file.layout.ConversionPattern=%d{ABSOLUTE} %5p %c{1}:%L - %m%n

# Direct log messages to stdout


log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Target=System.out
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d{ABSOLUTE} %5p %c{1}:%L - %m%n

# Root logger option


log4j.rootLogger=INFO, file, stdout

# Log everything. Good for troubleshooting


log4j.logger.org.hibernate=INFO

# Log all JDBC parameters


log4j.logger.org.hibernate.type=ALL
12) Hibernate Inheritance Mapping Tutorial
-------------------------------------------
We can map the inheritance hierarchy classes with the table of the database. There
are three inheritance mapping strategies defined in the hibernate:

Table Per Hierarchy


Table Per Concrete class
Table Per Subclass

Leave for now, If asked in interview then prepare.

13) Hibernate One to Many Example using Annotation


-----------------------------------------------------

a) Question.java

package com.javatpoint;
import javax.persistence.*;
import java.util.List;

@Entity
@Table(name="q5991")
public class Question {
@Id
@GeneratedValue(strategy=GenerationType.TABLE)
private int id;
private String qname;

@OneToMany(cascade = CascadeType.ALL)
@JoinColumn(name="qid")
@OrderColumn(name="type")
private List<Answer> answers;
//sertters and getters
}

b) Answer.java

package com.javatpoint;

import javax.persistence.*;

@Entity
@Table(name="ans5991")
public class Answer {
@Id
@GeneratedValue(strategy=GenerationType.TABLE)

private int id;


private String answername;
private String postedBy;
//setters and getters
}
c) Create the configuration file(hibernate.cfg.xml)
This file contains information about the database and mapping file.

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


<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 5.3//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-5.3.dtd">

<hibernate-configuration>

<session-factory>
<property name="hbm2ddl.auto">update</property>
<property name="dialect">org.hibernate.dialect.Oracle9Dialect</property>

<property
name="connection.url">jdbc:oracle:thin:@localhost:1521:xe</property>
<property name="connection.username">system</property>
<property name="connection.password">jtp</property>
<property
name="connection.driver_class">oracle.jdbc.driver.OracleDriver</property>
<mapping class="com.javatpoint.Question"/>
</session-factory>

</hibernate-configuration>

D) StoreData.java
package com.javatpoint;

import java.util.ArrayList;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.boot.Metadata;
import org.hibernate.boot.MetadataSources;
import org.hibernate.boot.registry.StandardServiceRegistry;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
public class StoreData {
public static void main(String[] args) {

StandardServiceRegistry ssr=new
StandardServiceRegistryBuilder().configure("hibernate.cfg.xml").build();
Metadata meta=new MetadataSources(ssr).getMetadataBuilder().build();

SessionFactory factory=meta.getSessionFactoryBuilder().build();
Session session=factory.openSession();

Transaction t=session.beginTransaction();

Answer ans1=new Answer();


ans1.setAnswername("Java is a programming language");
ans1.setPostedBy("Ravi Malik");

Answer ans2=new Answer();


ans2.setAnswername("Java is a platform");
ans2.setPostedBy("Sudhir Kumar");

Answer ans3=new Answer();


ans3.setAnswername("Servlet is an Interface");
ans3.setPostedBy("Jai Kumar");

Answer ans4=new Answer();


ans4.setAnswername("Servlet is an API");
ans4.setPostedBy("Arun");
ArrayList<Answer> list1=new ArrayList<Answer>();
list1.add(ans1);
list1.add(ans2);

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


list2.add(ans3);
list2.add(ans4);

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

14) Hibernate Transaction Management Example


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

The methods of Transaction interface are as follows:

void begin() starts a new transaction.


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

Example of Transaction Management in Hibernate


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

Session session = null;


Transaction tx = null;

try {
session = sessionFactory.openSession();
tx = session.beginTransaction();
//some action
tx.commit();

}catch (Exception ex) {


ex.printStackTrace();
tx.rollback();
}
finally {session.close();}

15) Hibernate Query Language (HQL)


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

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

database independent
supports polymorphic queries
easy to learn for Java Programmer

15) Query Interface


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

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

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


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

Example of HQL to get all the records


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

Example of HQL to get records with pagination


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

Example of HQL update query


Transaction tx=session.beginTransaction();
Query q=session.createQuery("update User set name=:n where id=:i");
q.setParameter("n","Udit Kumar");
q.setParameter("i",111);

int status=q.executeUpdate();
System.out.println(status);
tx.commit();

Example of HQL delete query


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

16) HQL with Aggregate functions


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

Example to get total salary of all the employees


Query q=session.createQuery("select sum(salary) from Emp");
List<Integer> list=q.list();
System.out.println(list.get(0));

17) HCQL (Hibernate Criteria Query Language)


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

Leave this for now, If asked in interview then preapare.

18) Hibernate Named Query


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

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

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

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

@NamedQueries(
{
@NamedQuery(
name = "findEmployeeByName",
query = "from Employee e where e.name = :name"
)
}
)

//Hibernate Named Query


TypedQuery query = session.getNamedQuery("findEmployeeByName");
query.setParameter("name","amit");

19) Caching in Hibernate


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

There are mainly two types of caching:


First Level Cache, and
Second Level Cache

First Level Cache:


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

Second Level Cache:


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

EH (Easy Hibernate) Cache


Swarm Cache
OS Cache
JBoss Cache

20) Hibernate Second Level Cache


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

SessionFactory holds the second level cache data. It is global for all the session
objects and not enabled by default.

Different vendors have provided the implementation of Second Level Cache.

There are four ways to use second level cache.

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


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

The cache-usage property can be applied to class or collection level in hbm.xml


file. The example to define cache usage is given below:

<cache usage="read-only" />

21) Hibernate Second Level Cache Example


-----------------------------------------

a) Employee.java

@Entity
@Table(name="emp1012")
@Cacheable
@Cache(usage=CacheConcurrencyStrategy.READ_ONLY)
public class Employee {
@Id
private int id;
private String name;
--
--
--
b) hibernate.cfg.xml

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


<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 5.2.0//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-5.2.0.dtd">

<hibernate-configuration>

<session-factory>
<property name="show_sql">true</property>
<property name="hbm2ddl.auto">update</property>
<property name="dialect">org.hibernate.dialect.Oracle9Dialect</property>

<property
name="connection.url">jdbc:oracle:thin:@localhost:1521:xe</property>
<property name="connection.username">system</property>
<property name="connection.password">jtp</property>
<property
name="connection.driver_class">oracle.jdbc.driver.OracleDriver</property>

<property name="cache.use_second_level_cache">true</property>
<property
name="cache.region.factory_class">org.hibernate.cache.ehcache.EhCacheRegionFactory<
/property>
<mapping class="com.javatpoint.Employee"/>
</session-factory>
</hibernate-configuration>

c) FetchTest.java
------------------
Session session1=factory.openSession();
Employee emp1=(Employee)session1.load(Employee.class,121);
System.out.println(emp1.getId()+" "+emp1.getName()+" "+emp1.getSalary());
session1.close();

Session session2=factory.openSession();
Employee emp2=(Employee)session2.load(Employee.class,121);
System.out.println(emp2.getId()+" "+emp2.getName()+" "+emp2.getSalary());
session2.close();
Second level cache is applicaton level cache.
Note: We are loading same employee entity for twice, Now the db call will be
executed for only once and the second time it will be fetched from second level
cache.
So performance will be improved.

22) Hibernate and Spring Integration


-------------------------------------
We can simply integrate hibernate application with spring application.

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


file.

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

23) Advantage of Spring framework with hibernate


-------------------------------------------------
The Spring framework provides HibernateTemplate class, so you don't need to follow
so many steps like create Configuration, BuildSessionFactory,
Session, beginning and committing transaction etc.

So it saves a lot of code.

24) Understanding problem without using spring


------------------------------------------------

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

//creating configuration
Configuration cfg=new Configuration();
cfg.configure("hibernate.cfg.xml");

//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(111,"arun",40000);


session.persist(e1);//persisting the object

t.commit();//transaction is commited
session.close();
As you can see in the code of sole hibernate, you have to follow so many steps.

25) Solution by using HibernateTemplate class of Spring Framework


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

Employee e1=new Employee(111,"arun",40000);


hibernateTemplate.save(e1);

26) Methods of HibernateTemplate class


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

No. Method Description


1) void persist(Object entity) persists the given object.
2) Serializable save(Object entity) persists the given object
and returns id.
3) void saveOrUpdate(Object entity) persists or updates the
given object. If id is found, it updates the record otherwise saves the record.
4) void update(Object entity) updates the given object.
5) void delete(Object entity) deletes the given object
on the basis of id.
6) Object get(Class entityClass, Serializable id) returns the persistent
object on the basis of given id.
7) Object load(Class entityClass, Serializable id) returns the persistent
object on the basis of given id.
8) List loadAll(Class entityClass) returns the all the
persistent objects.

Example:
-------------
2) Employee.java

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

package com.javatpoint;

public class Employee {


private int id;
private String name;
private float salary;

//getters and setters

3) employee.hbm.xml

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

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


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

<hibernate-mapping>
<class name="com.javatpoint.Employee" table="emp558">
<id name="id">
<generator class="assigned"></generator>
</id>

<property name="name"></property>
<property name="salary"></property>
</class>

</hibernate-mapping>
4) EmployeeDao.java

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

package com.javatpoint;
import org.springframework.orm.hibernate3.HibernateTemplate;
import java.util.*;
public class EmployeeDao {
HibernateTemplate template;
public void setTemplate(HibernateTemplate template) {
this.template = template;
}
//method to save employee
public void saveEmployee(Employee e){
template.save(e);
}
//method to update employee
public void updateEmployee(Employee e){
template.update(e);
}
//method to delete employee
public void deleteEmployee(Employee e){
template.delete(e);
}
//method to return one employee of given id
public Employee getById(int id){
Employee e=(Employee)template.get(Employee.class,id);
return e;
}
//method to return all employees
public List<Employee> getEmployees(){
List<Employee> list=new ArrayList<Employee>();
list=template.loadAll(Employee.class);
return list;
}
}

5) applicationContext.xml
In this file, we are providing all the informations of the database in the
BasicDataSource object. This object is used in the LocalSessionFactoryBean class
object,
containing some other informations such as mappingResources and
hibernateProperties. The object of LocalSessionFactoryBean class is used in the
HibernateTemplate class. Let's see the code of applicationContext.xml file.

hibernate template
File: applicationContext.xml

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


<beans
xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">

<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">


<property name="driverClassName"
value="oracle.jdbc.driver.OracleDriver"></property>
<property name="url"
value="jdbc:oracle:thin:@localhost:1521:xe"></property>
<property name="username" value="system"></property>
<property name="password" value="oracle"></property>
</bean>

<bean id="mysessionFactory"
class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource"></property>

<property name="mappingResources">
<list>
<value>employee.hbm.xml</value>
</list>
</property>

<property name="hibernateProperties">
<props>
<prop
key="hibernate.dialect">org.hibernate.dialect.Oracle9Dialect</prop>
<prop key="hibernate.hbm2ddl.auto">update</prop>
<prop key="hibernate.show_sql">true</prop>

</props>
</property>
</bean>

<bean id="template"
class="org.springframework.orm.hibernate3.HibernateTemplate">
<property name="sessionFactory" ref="mysessionFactory"></property>
</bean>

<bean id="d" class="com.javatpoint.EmployeeDao">


<property name="template" ref="template"></property>
</bean>

</beans>

6) InsertTest.java

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

package com.javatpoint;

import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;

public class InsertTest {


public static void main(String[] args) {

Resource r=new ClassPathResource("applicationContext.xml");


BeanFactory factory=new XmlBeanFactory(r);

EmployeeDao dao=(EmployeeDao)factory.getBean("d");

Employee e=new Employee();


e.setId(114);
e.setName("varun");
e.setSalary(50000);

dao.saveEmployee(e);

}
}

You might also like