19 Hibernate
19 Hibernate
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:
¸ 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.
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:
1 hibernate.dialect
This property makes Hibernate generate the appropriate SQL for the
chosen database.
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.
∑ 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.
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.
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.
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();
}
}
%>