0% found this document useful (0 votes)
23 views11 pages

19 Hibernate

Hibernate is an ORM tool for Java that maps Java classes to database tables. It handles object-relational mapping and reduces programming tasks related to data persistence. Hibernate sits between Java objects and the database to handle persisting objects based on ORM mechanisms. It maps Java classes and data types to database tables and SQL data types and provides facilities to query and retrieve data.

Uploaded by

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

19 Hibernate

Hibernate is an ORM tool for Java that maps Java classes to database tables. It handles object-relational mapping and reduces programming tasks related to data persistence. Hibernate sits between Java objects and the database to handle persisting objects based on ORM mechanisms. It maps Java classes and data types to database tables and SQL data types and provides facilities to query and retrieve data.

Uploaded by

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

JAVA

HIBERNATE
Hibernate is an Object-Relational Mapping (ORM) solution for JAVA. 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.
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 and can
significantly reduce development time otherwise spent with manual data handling in SQL and
JDBC. Hibernate solves Object-Relational impedance mismatch problems by replacing direct
persistence-related database accesses with high-level object handling functions.

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
Advantages
1. Lets business code access objects rather than DB tables.
2. Hides details of SQL queries from OO logic.
3. No need to deal with the database implementation.
4. Entities based on business concepts rather than database structure.
5. Transaction management and automatic key generation.
6. Fast development of application.
Hibernate Advantages:

IPSR Solutions Ltd www.ipsr.edu.in 1


JAVA

¸ Hibernate takes care of mapping Java classes to database tables using XML files and
without writing any line of code.
¸ Provides simple APIs for storing and retrieving Java objects directly to and from the
database.
¸ If there is change in Database or in any table then the only need to change XML file
properties.
¸ Abstract away the unfamiliar SQL types and provide us to work around familiar Java
Objects.
¸ Hibernate does not require an application server to operate.
¸ Manipulates Complex associations of objects of your database.
¸ Minimize database access with smart fetching strategies.
¸ Provides simple querying of data.
Hibernate Architecture
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.

Following is a detailed view of the Hibernate Application Architecture with few important core
classes.

IPSR Solutions Ltd www.ipsr.edu.in 2


JAVA

JDBC provides a rudimentary level of abstraction of functionality common to relational


databases, allowing almost any database with a JDBC driver to be supported by Hibernate.
JNDI and JTA allow Hibernate to be integrated with J2EE application servers.
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 key components:
Database Connection: This is handled through one or more configuration files supported by
Hibernate. These files are hibernate.properties and hibernate.cfg.xml.
Class Mapping Setup: This component creates the connection between the Java classes and
database tables..
SessionFactory Object: Configuration object is used to create a SessionFactory object which
in turn configures Hibernate for the application using the supplied configuration file and allows

IPSR Solutions Ltd www.ipsr.edu.in 3


JAVA

for a Session object to be instantiated. The SessionFactory is a thread safe object and used by all
the threads of an application.
Session Object: 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.
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).
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.
Criteria Object: Criteria object are used to create and execute object oriented criteria queries
to retrieve objects.

Hibernate Configuration
Hibernate requires to know in advance where to find the mapping information that defines how
your Java classes relate to the database tables. Hibernate also requires a set of configuration
settings related to database and other related parameters. All such information is usually
supplied as standard Java properties file called hibernate.properties, or as an XML file named
hibernate.cfg.xml.
Hibernate Properties:

S.N. Properties and Description

1 hibernate.dialect
This property makes Hibernate generate the appropriate SQL for the
chosen database.

IPSR Solutions Ltd www.ipsr.edu.in 4


JAVA

2 hibernate.connection.driver_class
The JDBC driver class.

3 hibernate.connection.url
The JDBC URL to the database instance.

4 hibernate.connection.username
The database username.

5 hibernate.connection.password
The database password.

6 hibernate.connection.pool_size
Limits the number of connections waiting in the Hibernate database
connection pool.

7 hibernate.connection.autocommit
Allows autocommit mode to be used for the JDBC connection.

Hibernate Persistent Class


Java classes whose objects or instances will be stored in database tables are called persistent
classes in Hibernate. Hibernate works best if these classes follow some simple rules, also
known as the Plain Old Java Object (POJO) programming model. There are following main
rules of persistent classes:
∑ All Java classes that will be persisted need a default constructor.
∑ All classes should contain an ID in order to allow easy identification of your objects
within Hibernate and the database. This property maps to the primary key column of a
database table.
∑ All attributes that will be persisted should be declared private and have getXXX and
setXXX methods defined in the JavaBean style.
IPSR Solutions Ltd www.ipsr.edu.in 5
JAVA

∑ A central feature of Hibernate, proxies, depends upon the persistent class being either
non-final, or the implementation of an interface that declares all public methods.
Hibernate Mapping Files
An Object/relational mappings are usually defined in an XML document. This mapping file
instructs Hibernate how to map the defined class or classes to the database tables.
You should save the mapping document in a file with the format <classname>.hbm.xml.
∑ The mapping document is an XML document having <hibernate-mapping> as the root
element which contains all the <class> elements.

∑ The <class> elements are used to define specific mappings from a Java classes to the
database tables. The Java class name is specified using the name attribute of the class
element and the database table name is specified using the table attribute.

∑ The <meta> element is optional element and can be used to create the class description.

∑ The <id> element maps the unique ID attribute in class to the primary key of the
database table. The name attribute of the id element refers to the property in the class and
the column attribute refers to the column in the database table. The type attribute holds
the hibernate mapping type, this mapping types will convert from Java to SQL data type.

∑ The <generator> element within the id element is used to automatically generate the
primary key values.

∑ The <property> element is used to map a Java class property to a column in the database
table. The name attribute of the element refers to the property in the class and the column
attribute refers to the column in the database table. The type attribute holds the hibernate
mapping type, this mapping types will convert from Java to SQL data type.

IPSR Solutions Ltd www.ipsr.edu.in 6


JAVA

Hibernate Query Language


Hibernate Query Language (HQL) is an object-oriented query language, similar to SQL, but
instead of operating on tables and columns, HQL works with persistent objects and their
properties. HQL queries are translated by Hibernate into conventional SQL queries which in
turns perform action on database.

Keywords like SELECT , FROM and WHERE etc. are not case sensitive but properties like
table and column names are case sensitive in HQL.
FROM Clause:
You will use FROM clause if you want to load a complete persistent objects into memory.

AS Clause
The AS clause can be used to assign aliases to the classes in your HQL queries, specially when
you have long queries.

SELECT Clause
The SELECT clause provides more control over the result set than the FROM clause. If you
want to obtain few properties of objects instead of the complete object, use the SELECT clause.

WHERE Clause
If you want to narrow the specific objects that are returned from storage, you use the WHERE
clause.

IPSR Solutions Ltd www.ipsr.edu.in 7


JAVA

Using Named Parameters


Hibernate supports named parameters in its HQL queries. This makes writing HQL queries that
accept input from the user easy.

UPDATE Clause
The Query interface contains a method called executeUpdate() for executing HQL UPDATE or
DELETE statements.

DELETE Clause

INSERT Clause
HQL supports INSERT INTO clause only where records can be inserted from one object to
another object.

IPSR Solutions Ltd www.ipsr.edu.in 8


JAVA

Using Hibernate in a Web Application


The steps are:
1. Create the Database: Create a database and tables in MySql
2. Create a web application : Select Hibernate framework
3. Modify the Hibernate Configuration File:
∑ Open hibernate.cfg.xml in the Design tab.
∑ In the multi-view XML editor, expand the Configuration Properties node under
Optional Properties.
∑ Click Add to open the Add Hibernate Property dialog box.
∑ In the dialog box, select the hibernate.show_sql property and set the value to true.
This enables the debug logging of the SQL statements.
∑ Expand the Miscellaneous Properties node and click Add.
∑ In the dialog box, select the properties hibernate.current_session_context_class and
set the value to thread to enable Hibernate's automatic session context management.
∑ Click Add again under the Miscellaneous Properties node and select
hibernate.query.factory_class in the Property Name dropdown list.
∑ Select org.hibernate.hql.ast.ASTQueryTranslatorFactory as the Property Value.
Click OK.
4. Create the HibernateUtil.java Helper File: right click source packages node and add
HibernateUtil.java
5. Generate Hibernate Mapping Files and Java Classes: Create the Hibernate Reverse
Engineering File. The reverse engineering file enables you to have greater control over the
IPSR Solutions Ltd www.ipsr.edu.in 9
JAVA

database mapping strategy. The Hibernate Reverse Engineering Wizard creates a reverse
engineering file with a default configuration that you can edit in the XML editor. Create
the Hibernate Mapping Files and POJOs.
6. Create a java class as a helper class. The query methods can be written in this class.
Session session = null;
public Helper()
{
this.session = HibernateUtil.getSessionFactory().getCurrentSession();
}
public List getData()
{
List <Tab1> list=null;
try {
org.hibernate.Transaction tx = session.beginTransaction();
Query q = session.createQuery("from Tab1 as tab ");
list = (List<Tab1>) q.list();
} catch (Exception e) {
e.printStackTrace();
}
return list;
}
public void insert()
{
try
{
org.hibernate.Transaction tx=session.beginTransaction();
Query q=session.createQuery("insert into Tab1 (id,name) select regNo,name from
Details");
IPSR Solutions Ltd www.ipsr.edu.in 10
JAVA

q.executeUpdate();
tx.commit();
tx.rollback();
}
catch(Exception ex)
{
ex.printStackTrace();
}
}

7. Create a user interface (jsp) and call the methods.


<%
Helper hp=new Helper();
hp.insert();
List list = hp.getData();
Iterator it=list.iterator();
while(it.hasNext())
{
Tab1 t=(Tab1)it.next();
out.println(t.getId() + t.getName());
}

%>

IPSR Solutions Ltd www.ipsr.edu.in 11

You might also like