Vous êtes sur la page 1sur 34

1

HIBERNATE INTERVIEW QUESTIONS AND ANSWERS


1.What is ORM ?
ORM stands for object/relational mapping. ORM is the automated persistence of objects in a
Java application to the tables in a relational database.
2.What does ORM consists of ?
An ORM solution consists of the followig four pieces:

API for performing basic CRUD operations


API to express queries refering to classes
Facilities to specify metadata
Optimization facilities : dirty checking,lazy associations fetching

3.What are the ORM levels ?


The ORM levels are:

Pure relational (stored procedure.)


Light objects mapping (JDBC)
Medium object mapping
Full object Mapping (composition,inheritance, polymorphism, persistence by
reachability)

4.What is Hibernate?
Hibernate is a pure Java object-relational mapping (ORM) and persistence framework that
allows you to map plain old Java objects to relational database tables using (XML)
configuration files.Its purpose is to relieve the developer from a significant amount of
relational data persistence-related programming tasks.
5.Why do you need ORM tools like hibernate?
The main advantage of ORM like hibernate is that it shields developers from messy SQL.
Apart from this, ORM provides following benefits:

Improved productivity
o High-level object-oriented API
o Less Java code to write
o No SQL to write
Improved performance
o Sophisticated caching
o Lazy loading
o Eager loading
Improved maintainability
o A lot less code to write
Improved portability
o ORM framework generates database-specific SQL for you

2
6.What Does Hibernate Simplify?
Hibernate simplifies:

Saving and retrieving your domain objects


Making database column and table name changes
Centralizing pre save and post retrieve logic
Complex joins for retrieving related items
Schema creation from object model

7. What is the need for Hibernate xml mapping file?


Hibernate mapping file tells Hibernate which tables and columns to use to load and store
objects. Typical mapping file look as follows:

8.What are the most common methods of Hibernate configuration?


The most common methods of Hibernate configuration are:

Programmatic configuration
XML configuration (hibernate.cfg.xml)

9.What are the important tags of hibernate.cfg.xml?


Following are the important tags of hibernate.cfg.xml:

10.What are the Core interfaces are of Hibernate framework?


The five core interfaces are used in just about every Hibernate application. Using these
interfaces, you can store and retrieve persistent objects and control transactions.

Session interface
SessionFactory interface
Configuration interface
Transaction interface
Query and Criteria interfaces

11.What role does the Session interface play in Hibernate?


The Session interface is the primary interface used by Hibernate applications. It is a singlethreaded, short-lived object representing a conversation between the application and the
persistent store. It allows you to create query objects to retrieve persistent objects.
Session session = sessionFactory.openSession();
Session interface role:

Wraps a JDBC connection


Factory for Transaction
Holds a mandatory (first-level) cache of persistent objects, used when navigating the
object graph or looking up objects by identifier

12.What role does the SessionFactory interface play in Hibernate?


The application obtains Session instances from a SessionFactory. There is typically a single
SessionFactory for the whole applicationreated during application initialization. The
SessionFactory caches generate SQL statements and other mapping metadata that
Hibernate uses at runtime. It also holds cached data that has been read in one unit of work
and may be reused in a future unit of work
SessionFactory sessionFactory = configuration.buildSessionFactory();

13.What is the general flow of Hibernate communication with RDBMS?


The general flow of Hibernate communication with RDBMS is :

Load the Hibernate configuration file and create configuration object. It will
automatically load all hbm mapping files
Create session factory from configuration object
Get one session from this session factory
Create HQL Query
Execute query to get list containing Java objects

14.What is Hibernate Query Language (HQL)?


Hibernate offers a query language that embodies a very powerful and flexible mechanism to
query, store, update, and retrieve objects from a database. This language, the Hibernate
query Language (HQL), is an object-oriented extension to SQL.
15.How do you map Java Objects with Database tables?

First we need to write Java domain objects (beans with setter and getter).
Write hbm.xml, where we map java class to table and database columns to Java
class variables.

Example :
<hibernate-mapping>
<class name="com.test.User" table="user">
<property column="USER_NAME" length="255"
name="userName" not-null="true" type="java.lang.String"/>
<property column="USER_PASSWORD" length="255"
name="userPassword" not-null="true" type="java.lang.String"/>
</class>
</hibernate-mapping>

16.Whats the difference between load() and get()?

5
load() vs. get() :load()

get()

Only use the load() method if you are sure that


the object exists.

If you are not sure that the object exists,


then use one of the get() methods.

load() method will throw an exception if the


unique id is not found in the database.

get() method will return null if the


unique id is not found in the database.

load() just returns a proxy by default and


database wont be hit until the proxy is first
invoked.

get() will hit the database immediately.

17.What is the difference between and merge and update ?


Use update() if you are sure that the session does not contain an already persistent
instance with the same identifier, and merge() if you want to merge your modifications at
any time without consideration of the state of the session.
18.How do you define sequence generated primary key in hibernate?
Using <generator> tag.
Example:<id column="USER_ID" name="id" type="java.lang.Long">
<generator class="sequence">
<param name="table">SEQUENCE_NAME</param>
<generator>
</id>
19.Define cascade and inverse option in one-many mapping?
cascade - enable operations to cascade to child entities.
cascade="all|none|save-update|delete|all-delete-orphan"
inverse - mark this collection as the "inverse" end of a bidirectional association.
inverse="true|false"
Essentially "inverse" indicates which end of a relationship should be ignored, so when
persisting a parent who has a collection of children, should you ask the parent for its list of
children, or ask the children who the parents are?
20.What do you mean by Named SQL query?

6
Named SQL queries are defined in the mapping xml document and called wherever
required.
Example:
<sql-query name = "empdetails">
<return alias="emp" class="com.test.Employee"/>
SELECT emp.EMP_ID AS {emp.empid},
emp.EMP_ADDRESS AS {emp.address},
emp.EMP_NAME AS {emp.name}
FROM Employee EMP WHERE emp.NAME LIKE :name
</sql-query>
Invoke Named Query :
List people = session.getNamedQuery("empdetails")
.setString("TomBrady", name)
.setMaxResults(50)
.list();
21.How do you invoke Stored Procedures?
<sql-query name="selectAllEmployees_SP" callable="true">
<return alias="emp" class="employee">
<return-property name="empid" column="EMP_ID"/>
<return-property name="name" column="EMP_NAME"/>
<return-property name="address" column="EMP_ADDRESS"/>
{ ? = call selectAllEmployees() }
</return>
</sql-query>
22.Explain Criteria API
Criteria is a simplified API for retrieving entities by composing Criterion objects. This is a
very convenient approach for functionality like "search" screens where there is a variable
number of conditions to be placed upon the result set.
Example :
List employees = session.createCriteria(Employee.class)
.add(Restrictions.like("name", "a%") )
.add(Restrictions.like("address", "Boston"))
.addOrder(Order.asc("name") )
.list();
23.Define HibernateTemplate?
org.springframework.orm.hibernate.HibernateTemplate is a helper class which provides
different methods for querying/retrieving data from the database. It also converts checked
HibernateExceptions into unchecked DataAccessExceptions.

24.What are the benefits does HibernateTemplate provide?


The benefits of HibernateTemplate are :

HibernateTemplate, a Spring Template class simplifies interactions with Hibernate


Session.
Common functions are simplified to single method calls.
Sessions are automatically closed.
Exceptions are automatically caught and converted to runtime exceptions.

25.How do you switch between relational databases without code changes?


Using Hibernate SQL Dialects , we can switch databases. Hibernate will generate
appropriate hql queries based on the dialect defined.
26.If you want to see the Hibernate generated SQL statements on console, what
should we do?
In Hibernate configuration file set as follows:
<property name="show_sql">true</property>

27.What are derived properties?


The properties that are not mapped to a column, but calculated at runtime by evaluation of
an expression are called derived properties. The expression can be defined using the
formula attribute of the element.
28.What is component mapping in Hibernate?

A component is an object saved as a value, not as a reference


A component can be saved directly without needing to declare interfaces or identifier
properties
Required to define an empty constructor
Shared references not supported

Example:

29.What is the difference between sorted and ordered collection in hibernate?


sorted collection vs. order collection :sorted collection

order collection

A sorted collection is sorting a collection by


utilizing the sorting features provided by the
Java collections framework. The sorting
occurs in the memory of JVM which running
Hibernate, after the data being read from
database using java comparator.

Order collection is sorting a collection by


specifying the order-by clause for sorting
this collection when retrieval.

If your collection is not large, it will be more


efficient way to sort it.

If your collection is very large, it will be


more efficient way to sort it .

31.What is the advantage of Hibernate over jdbc?

9
Hibernate Vs. JDBC :JDBC

Hibernate

With JDBC, developer has to write code to


map an object model's data representation
to a relational data model and its
corresponding database schema.

Hibernate is flexible and powerful ORM


solution to map Java classes to database
tables. Hibernate itself takes care of this
mapping using XML files so developer does
not need to write code for this.

With JDBC, the automatic mapping of Java


objects with database tables and vice versa
conversion is to be taken care of by the
developer manually with lines of code.

Hibernate provides transparent persistence


and developer does not need to write code
explicitly to map database tables tuples to
application objects during interaction with
RDBMS.

JDBC supports only native Structured Query


Language (SQL). Developer has to find out
the efficient way to access database, i.e. to
select effective query from a number of
queries to perform same task.

Hibernate provides a powerful query


language Hibernate Query Language
(independent from type of database) that is
expressed in a familiar SQL like syntax and
includes full support for polymorphic queries.
Hibernate also supports native SQL
statements. It also selects an effective way
to perform a database manipulation task for
an application.

Application using JDBC to handle persistent


data (database tables) having database
specific code in large amount. The code
written to map table data to application
objects and vice versa is actually to map
table fields to object properties. As table
changed or database changed then its
essential to change object structure as well
as to change code written to map table-toobject/object-to-table.

Hibernate provides this mapping itself. The


actual mapping between tables and
application objects is done in XML files. If
there is change in Database or in any table
then the only need to change XML file
properties.

With JDBC, it is developers responsibility to


handle JDBC result set and convert it to Java
objects through code to use this persistent
data in application. So with JDBC, mapping
between Java objects and database tables is

Hibernate reduces lines of code by


maintaining object-table mapping itself and
returns result to application in form of Java
objects. It relieves programmer from manual
handling of persistent data, hence reducing
the development time and maintenance

10

done manually.

cost.

With JDBC, caching is maintained by handcoding.

Hibernate, with Transparent Persistence,


cache is set to application work space.
Relational tuples are moved to this cache as
a result of query. It improves performance if
client application reads same data many
times for same write. Automatic Transparent
Persistence allows the developer to
concentrate more on business logic rather
than this application code.

In JDBC there is no check that always every


user has updated data. This check has to be
added by the developer.

Hibernate enables developer to define


version type field to application, due to this
defined field Hibernate updates version field
of database table every time relational tuple
is updated in form of Java class object to
that table. So if two users retrieve same
tuple and then modify it and one user save
this modified tuple to database, version is
automatically updated for this tuple by
Hibernate. When other user tries to save
updated tuple to database then it does not
allow saving it because this user does not
have updated data.

32.What are the Collection types in Hibernate ?

Bag
Set
List
Array
Map

33.What are the ways to express joins in HQL?


HQL provides four ways of expressing (inner and outer) joins:

An implicit association join


An ordinary join in the FROM clause
A fetch join in the FROM clause.
A theta-style join in the WHERE clause.

11

34.Define cascade and inverse option in one-many mapping?


cascade - enable operations to cascade to child entities.
cascade="all|none|save-update|delete|all-delete-orphan"
inverse - mark this collection as the "inverse" end of a bidirectional association.
inverse="true|false"
Essentially "inverse" indicates which end of a relationship should be ignored, so when
persisting a parent who has a collection of children, should you ask the parent for its list of
children, or ask the children who the parents are?
35.What is Hibernate proxy?
The proxy attribute enables lazy initialization of persistent instances of the class. Hibernate
will initially return CGLIB proxies which implement the named interface. The actual
persistent object will be loaded when a method of the proxy is invoked.
36.How can Hibernate be configured to access an instance variable directly and
not through a setter method ?
By mapping the property with access="field" in Hibernate metadata. This forces hibernate
to bypass the setter method and access the instance variable directly while initializing a
newly loaded object.
37.How can a whole class be mapped as immutable?
Mark the class as mutable="false" (Default is true),. This specifies that instances of the
class are (not) mutable. Immutable classes, may not be updated or deleted by the
application.
38.What is the use of dynamic-insert and dynamic-update attributes in a class
mapping?
Criteria is a simplified API for retrieving entities by composing Criterion objects. This is a
very convenient approach for functionality like "search" screens where there is a variable
number of conditions to be placed upon the result set.

dynamic-update (defaults to false): Specifies that UPDATE SQL should be generated


at runtime and contain only those columns whose values have changed
dynamic-insert (defaults to false): Specifies that INSERT SQL should be generated at
runtime and contain only the columns whose values are not null.

39.What do you mean by fetching strategy ?


A fetching strategy is the strategy Hibernate will use for retrieving associated objects if the
application needs to navigate the association. Fetch strategies may be declared in the O/R
mapping metadata, or over-ridden by a particular HQL or Criteria query.

12
40.What is automatic dirty checking?
Automatic dirty checking is a feature that saves us the effort of explicitly asking Hibernate
to update the database when we modify the state of an object inside a transaction.
41.What is transactional write-behind?
Hibernate uses a sophisticated algorithm to determine an efficient ordering that avoids
database foreign key constraint violations but is still sufficiently predictable to the user. This
feature is called transactional write-behind.
42.What are Callback interfaces?
Callback interfaces allow the application to receive a notification when something interesting
happens to an objectfor example, when an object is loaded, saved, or deleted. Hibernate
applications don't need to implement these callbacks, but they're useful for implementing
certain kinds of generic functionality.
43.What are the types of Hibernate instance states ?
Three types of instance states:

Transient -The instance is not associated with any persistence context


Persistent -The instance is associated with a persistence context
Detached -The instance was associated with a persistence context which has been
closed currently not associated

44.What are the differences between EJB 3.0 & Hibernate


Hibernate Vs EJB 3.0 :Hibernate

EJB 3.0

SessionCache or collection of loaded


objects relating to a single unit of work

Persistence Context-Set of entities that


can be managed by a given EntityManager
is defined by a persistence unit

XDoclet Annotations used to support


Attribute Oriented Programming

Java 5.0 Annotations used to support


Attribute Oriented Programming

Defines HQL for expressing queries to the


database

Defines EJB QL for expressing queries

Supports Entity Relationships through


mapping files and annotations in JavaDoc

Support Entity Relationships through


Java 5.0 annotations

13

Provides a Persistence Manager API


exposed via the Session, Query, Criteria, and
Transaction API

Provides and Entity Manager Interface


for managing CRUD operations for an Entity

Provides callback support through


lifecycle, interceptor, and validatable
interfaces

Provides callback support through Entity


Listener and Callback methods

Entity Relationships are unidirectional.


Bidirectional relationships are implemented
by two unidirectional relationships

Entity Relationships are bidirectional or


unidirectional

45.What are the types of inheritance models in Hibernate?


There are three types of inheritance models in Hibernate:

Table per class hierarchy


Table per subclass
Table per concrete class

HIBERNATE TUTORILA FROM JAVATPOINT


This hibernate tutorial provides in-depth concepts of Hibernate Framework with simplified
examples. It was started in 2001 by Gavin King as an alternative to EJB2 style entity bean.
The stable release of Hibernate till July 16, 2014, is hibernate 4.3.6. It is helpful for
beginners and experienced persons.
Hibernate Framework
Hibernate framework simplifies the development of java application to interact with the
database. Hibernate is an open source, lightweight, ORM (Object Relational Mapping) 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.

14
The ORM tool internally uses the JDBC API to interact with the database.
Advantages of Hibernate Framework
There are many advantages of Hibernate Framework. They are as follows:
1) Opensource and Lightweight: Hibernate framework is opensource 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 bydefault.
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: To fetch data form 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
1. Hibernate Architecture
2. Elements of Hibernate Architecture
1. SessionFactory
2. Session
3. Transaction
4. ConnectionProvider
5. TransactionFactory
The Hibernate architecture includes many objects persistent object, session factory,
transaction factory, connection factory, session, transaction etc.
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:

15

This is the high level architecture of Hibernate with mapping file and configuration file.

16

Hibernate framework uses many objects 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
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.

17
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.
Generator classes in Hibernate
1. Hibernate Architecture
2. Hibernate Framework
3. Advantages of Hibernate Framework
The <generator> subelement of id 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:
1. assigned
2. increment
3. sequence
4. hilo
5. native
6. identity
7. seqhilo
8. uuid
9. guid
10. select
11. foreign
12. 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:
1. ....
2. <hibernate-mapping>

18
3.
<class ...>
4.
<id ...>
5.
<generator class="assigned"></generator>
6.
</id>
7.
8.
.....
9.
10. </class>
11. </hibernate-mapping>
2) increment
It generates the unique id only if no other process is inserting data into this table. It
generates short, int or long type identifier. The first generated identifier is 1 normally and
incremented as 1. Syntax:
1. ....
2. <hibernate-mapping>
3.
<class ...>
4.
<id ...>
5.
<generator class="increment"></generator>
6.
</id>
7.
8.
.....
9.
10. </class>
11. </hibernate-mapping>
3) sequence
It uses the sequence of the database. if there is no sequence defined, it creates a sequence
automatically e.g. in case of Oracle database, it creates a sequence named
HIBERNATE_SEQUENCE. In case of Oracle, DB2, SAP DB, Postgre SQL or McKoi, it uses
sequence but it uses generator in interbase. Syntax:
1. .....
2. <id ...>
3.
<generator class="sequence"></generator>
4. </id>
5. .....
For defining your own sequence, use the param subelement of generator.
1. .....
2. <id ...>
3.
<generator class="sequence">
4.
<param name="sequence">your_sequence_name</param>
5.
</generator>
6. </id>
7. .....

19
4) hilo
It uses high and low algorithm to generate the id of type short, int and long. Syntax:
1. .....
2. <id ...>
3.
<generator class="hilo"></generator>
4. </id>
5. .....
5) native
It uses identity, sequence or hilo depending on the database vendor. Syntax:
1. .....
2. <id ...>
3.
<generator class="native"></generator>
4. </id>
5. .....
6) identity
It is used in Sybase, My SQL, MS SQL Server, DB2 and HypersonicSQL to support the id
column. The returned id is of type short, int or long.
7) seqhilo
It uses high and low algorithm on the specified sequence name. The returned id is of type
short, int or long.
8) uuid
It uses 128-bit UUID algorithm to generate the id. The returned id is of type String, unique
within a network (because IP is used). The UUID is represented in hexadecimal digits, 32 in
length.
9) guid
It uses GUID generated by database of type string. It works on MS SQL Server and MySQL.
10) select
It uses the primary key returned by the database trigger.
11) foreign
It uses the id of another associated object, mostly used with <one-to-one> association.

20
12) sequence-identity
It uses a special sequence generation strategy. It is supported in Oracle 10g drivers only.

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 MyISAM org.hibernate.dialect.MySQLMyISAMDialect
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

21
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

Caching in Hibernate
1. Caching in Hibernate
2. First Level Cache
3. Second Level Cache
Hibernate caching improves the performance of the application by pooling the object in the
cache.
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.
Second Level Cache implementations are provided by different vendors such as:

EH (Easy Hibernate) Cache


Swarm Cache
OS Cache
JBoss Cache

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.

22
Different vendors have provided the implementation of Second Level Cache.
1.
2.
3.
4.

EH Cache
OS Cache
Swarm Cache
JBoss Cache

Each implementation provides different cache usage functionality. There are four ways to
use second level cache.
1.
2.
3.
4.

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:
1. <cache usage="read-only" />
Let's see the second level cache implementation and cache usage.
Implementation read-only nonstrict-read-write read-write transactional
EH Cache

Yes

Yes

Yes

No

OS Cache

Yes

Yes

Yes

No

Swarm Cache

Yes

Yes

No

No

JBoss Cache

No

No

No

Yes

3 extra steps for second level cache example using EH cache


1) Add 2 configuration setting in hibernate.cfg.xml file
1. <property name="cache.provider_class">org.hibernate.cache.EhCacheProvider</pro
perty>
2. <property name="hibernate.cache.use_second_level_cache">true</property>
2) Add cache usage setting in hbm file
1. <cache usage="read-only" />
3) Create ehcache.xml file
1. <?xml version="1.0"?>
2. <ehcache>
3.

23
4.
5.
6.
7.
8.

<defaultCache
maxElementsInMemory="100"
eternal="true"/>
</ehcache>

Hibernate Second Level Cache Example


To understand the second level cache through example, we need to create following pages:
1.
2.
3.
4.
5.

Employee.java
employee.hbm.xml
hibernate.cfg.xml
ehcache.xml
FetchTest.java

Here, we are assuming, there is emp1012 table in the oracle database containing
some records.
File: Employee.java
1. package com.javatpoint;
2.
3. public class Employee {
4. private int id;
5. private String name;
6. private float salary;
7.
8. public Employee() {}
9. public Employee(String name, float salary) {
10.
super();
11.
this.name = name;
12.
this.salary = salary;
13. }
14. //setters and getters
15. }
File: employee.hbm.xml
1. <?xml version='1.0' encoding='UTF-8'?>
2. <!DOCTYPE hibernate-mapping PUBLIC
3.
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
4.
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
5.
6.
<hibernate-mapping>
7.
<class name="com.javatpoint.Employee" table="emp1012">
8.
<cache usage="read-only" />
9.
<id name="id">
10.
<generator class="native"></generator>
11.
</id>
12.
<property name="name"></property>
13.
<property name="salary"></property>

24
14.
15.
16.

</class>
</hibernate-mapping>

Here, we are using read-only cache usage for the class. The cache usage can also be used
in collection.
File: hibernate.cfg.xml
1. <?xml version='1.0' encoding='UTF-8'?>
2. <!DOCTYPE hibernate-configuration PUBLIC
3.
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
4.
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
5.
6. <!-- Generated by MyEclipse Hibernate Tools.
-->
7. <hibernate-configuration>
8.
9.
<session-factory>
10.
<property name="show_sql">true</property>
11.
<property name="hbm2ddl.auto">update</property>
12.
<property name="dialect">org.hibernate.dialect.Oracle9Dialect</property>
13.
<property name="connection.url">jdbc:oracle:thin:@localhost:1521:xe</prop
erty>
14.
<property name="connection.username">system</property>
15.
<property name="connection.password">oracle</property>
16.
<property name="connection.driver_class">oracle.jdbc.driver.OracleDriver</p
roperty>
17.
18.
<property name="cache.provider_class">org.hibernate.cache.EhCacheProvider
</property>
19.
<property name="hibernate.cache.use_second_level_cache">true</property>
20.
21.
<mapping resource="employee.hbm.xml"/>
22.
</session-factory>
23.
24. </hibernate-configuration>
To implement second level cache, we need to define cache.provider_class property in the
configuration file.
File: ehcache.xml
1.
2.
3.
4.
5.
6.
7.
8.
9.

<?xml version="1.0"?>
<ehcache>
<defaultCache
maxElementsInMemory="100"
eternal="false"
timeToIdleSeconds="120"
timeToLiveSeconds="200" />
<cache name="com.javatpoint.Employee"

25
10. maxElementsInMemory="100"
11. eternal="false"
12. timeToIdleSeconds="5"
13. timeToLiveSeconds="200" />
14. </ehcache>
You need to create ehcache.xml file to define the cache property.
defaultCache will be used for all the persistent classes. We can also define persistent class
explicitely by using the cache element.
eternal If we specify eternal="true", we don't need to define timeToIdleSeconds and
timeToLiveSeconds attributes because it will be handled by hibernate internally. Specifying
eternal="false" gives control to the programmer, but we need to define timeToIdleSeconds
and timeToLiveSeconds attributes.
timeToIdleSeconds It defines that how many seconds object can be idle in the second
level cache.
timeToLiveSeconds It defines that how many seconds object can be stored in the second
level cache whether it is idle or not.
File: FetchTest.java
1. package com.javatpoint;
2.
3. import org.hibernate.Session;
4. import org.hibernate.SessionFactory;
5. import org.hibernate.cfg.Configuration;
6.
7. public class FetchTest {
8. public static void main(String[] args) {
9. Configuration cfg=new Configuration().configure("hibernate.cfg.xml");
10. SessionFactory factory=cfg.buildSessionFactory();
11.
12.
Session session1=factory.openSession();
13.
Employee emp1=(Employee)session1.load(Employee.class,121);
14.
System.out.println(emp1.getId()+" "+emp1.getName()+" "+emp1.getSalary());
15.
session1.close();
16.
17.
Session session2=factory.openSession();
18.
Employee emp2=(Employee)session2.load(Employee.class,121);
19.
System.out.println(emp2.getId()+" "+emp2.getName()+" "+emp2.getSalary());
20.
session2.close();
21.
22. }
23. }

26
Output:

As we can see here, hibernate does not fire query twice. If you don't use second level
cache, hibernate will fire query twice because both query uses different session objects.
Hibernate Query Language (HQL)
1. Hibernate Query Language
2. Advantage of HQL
3. Query Interface
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

Query Interface
It is an object oriented representation of Hibernate Query. The object of Query can be
obtained by calling the createQuery() method Session interface.
The query interface provides many methods. There is given commonly used methods:
1. public int executeUpdate() is used to execute the update or delete query.
2. public List list() returns the result of the ralation as a list.
3. public Query setFirstResult(int rowno) specifies the row number from where
record will be retrieved.
4. public Query setMaxResult(int rowno) specifies the no. of records to be
retrieved from the relation (table).
5. public Query setParameter(int position, Object value) it sets the value to the
JDBC style query parameter.
6. public Query setParameter(String name, Object value) it sets the value to a
named query parameter.

27
Example of HQL to get all the records
1. Query query=session.createQuery("from Emp");//here persistent class name is Emp
2. List list=query.list();
Example of HQL to get records with pagination
1.
2.
3.
4.

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


1.
2.
3.
4.
5.
6.
7.
8.

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


1. Query query=session.createQuery("delete from Emp where id=100");
2. //specifying class name (Emp) not tablename
3. query.executeUpdate();
HQL with Aggregate functions
You may call avg(), min(), max() etc. aggregate functions by HQL. Let's see some common
examples:
Example to get total salary of all the employees
1. Query q=session.createQuery("select sum(salary) from Emp");
2. List<Emp> list=q.list();
3.
Iterator<Emp> itr=list.iterator();
4.
while(itr.hasNext()){
5.
System.out.println(itr.next());
6. }
Example to get maximum salary of employee
1. Query q=session.createQuery("select max(salary) from Emp");

28
Example to get minimum salary of employee
1. Query q=session.createQuery("select min(salary) from Emp");
Example to count total number of employee ID
1. Query q=session.createQuery("select count(id) from Emp");
Example to get average salary of each employees
1. Query q=session.createQuery("select avg(salary) from Emp");
HCQL (Hibernate Criteria Query Language)
1.
2.
3.
4.

Hibernate Criteria Query Language


Criteria Interface
Restrictions class
Examples of HCQL

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.
Advantage of HCQL
The HCQL provides methods to add criteria, so it is easy for the java programmer to add
criteria. The java programmer is able to add many criteria on a query.
Criteria Interface
The Criteria interface provides many methods to specify criteria. The object of Criteria can
be obtained by calling the createCriteria() method of Session interface.
Syntax of createCriteria() method of Session interface
1. public Criteria createCriteria(Class c)
The commonly used methods of Criteria interface are as follows:
1. public Criteria add(Criterion c) is used to add restrictions.
2. public Criteria addOrder(Order o) specifies ordering.
3. public Criteria setFirstResult(int firstResult) specifies the first number of record
to be retreived.
4. public Criteria setMaxResult(int totalResult) specifies the total number of
records to be retreived.
5. public List list() returns list containing object.
6. public Criteria setProjection(Projection projection) specifies the projection.

29
Restrictions class
Restrictions class provides methods that can be used as Criterion. The commonly used
methods of Restrictions class are as follows:
1. public static SimpleExpression lt(String propertyName,Object value) sets the
less than constraint to the given property.
2. public static SimpleExpression le(String propertyName,Object value) sets the
less than or equal constraint to the given property.
3. public static SimpleExpression gt(String propertyName,Object value) sets
the greater than constraint to the given property.
4. public static SimpleExpression ge(String propertyName,Object value) sets
the greater than or equal than constraint to the given property.
5. public static SimpleExpression ne(String propertyName,Object value) sets
the not equal constraint to the given property.
6. public static SimpleExpression eq(String propertyName,Object value) sets
the equal constraint to the given property.
7. public static Criterion between(String propertyName, Object low, Object
high) sets the between constraint.
8. public static SimpleExpression like(String propertyName, Object value) sets
the like constraint to the given property.
Order class
The Order class represents an order. The commonly used methods of Restrictions class are
as follows:
1. public static Order asc(String propertyName) applies the ascending order on
the basis of given property.
2. public static Order desc(String propertyName) applies the descending order on
the basis of given property.
Examples of Hibernate Criteria Query Language
There are given a lot of examples of HCQL.
Example of HCQL to get all the records
1. Crietria c=session.createCriteria(Emp.class);//passing Class class argument
2. List list=c.list();
Example of HCQL to get the 10th to 20th record
1.
2.
3.
4.

Crietria c=session.createCriteria(Emp.class);
c.setFirstResult(10);
c.setMaxResult(20);
List list=c.list();

30
Example of HCQL to get the records whose salary is greater than 10000
1. Crietria c=session.createCriteria(Emp.class);
2. c.add(Restrictions.gt("salary",10000));//salary is the propertyname
3. List list=c.list();
Example of HCQL to get the records in ascending order on the basis of salary
1. Crietria c=session.createCriteria(Emp.class);
2. c.addOrder(Order.asc("salary"));
3. List list=c.list();
HCQL with Projection
We can fetch data of a particular column by projection such as name etc. Let's see the
simple example of projection that prints data of NAME column of the table only.
1. Criteria c=session.createCriteria(Emp.class);
2. c.setProjection(Projections.property("name"));
3. List list=c.list();
Hibernate Named Query
1.
2.
3.
4.

Hibernate Named Query


Hibernate Named Query by annotation
Example of Hibernate Named Query by annotation
Hibernate Named Query by mapping file

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.
There are two ways to define the named query in hibernate:

by annotation
by mapping file.

Hibernate Named Query by annotation


If you want to use named query in hibernate, you need to have knowledge of
@NamedQueries and @NamedQuery annotations.
@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:
1. @NamedQueries(
2.
{

31
3.
4.
5.
6.
7.
}
8. )

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

Example of Hibernate Named Query by annotation


In this example, we are using annotations to defined the named query in the persistent
class. There are three files only:

Employee.java
hibernate.cfg.xml
FetchDemo

In this example, we are assuming that there is em table in the database containing 4
columns id, name, job and salary and there are some records in this table.
Employee.java
It is a persistent class that uses annotations to define named query and marks this class as
entity.
1. package com.javatpoint;
2.
3. import javax.persistence.*;
4. import javax.persistence.Entity;
5. import javax.persistence.GeneratedValue;
6. import javax.persistence.Id;
7.
8. @NamedQueries(
9.
{
10.
@NamedQuery(
11.
name = "findEmployeeByName",
12.
query = "from Employee e where e.name = :name"
13.
)
14.
}
15. )
16.
17. @Entity
18. @Table(name="em")
19. public class Employee {
20.
21.
public String toString(){return id+" "+name+" "+salary+" "+job;}
22.
23.
int id;
24.
String name;
25.
int salary;
26.
String job;
27.
@Id

32
28.
@GeneratedValue(strategy=GenerationType.AUTO)
29.
30.
//getters and setters
31. }
hibernate.cfg.xml
It is a configuration file that stores the informations about database such as driver class,
url, username, password and mapping class etc.
1. <?xml version='1.0' encoding='UTF-8'?>
2. <!DOCTYPE hibernate-configuration PUBLIC
3.
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
4.
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
5.
6. <hibernate-configuration>
7.
8.
<session-factory>
9.
<property name="hbm2ddl.auto">update</property>
10.
<property name="dialect">org.hibernate.dialect.Oracle9Dialect</property>
11.
<property name="connection.url">jdbc:oracle:thin:@localhost:1521:xe</prop
erty>
12.
<property name="connection.username">system</property>
13.
<property name="connection.password">oracle</property>
14.
<property name="connection.driver_class">oracle.jdbc.driver.OracleDriver</p
roperty>
15.
<mapping class="com.javatpoint.Employee"/>
16.
</session-factory>
17.
18. </hibernate-configuration>
FetchData.java
It is a java class that uses the named query and prints the informations based on the query.
The getNamedQuery method uses the named query and returns the instance of Query.
1. package com.javatpoint;
2.
3. import java.util.Iterator;
4. import java.util.List;
5.
6. import org.hibernate.cfg.AnnotationConfiguration;
7. import org.hibernate.*;
8.
9. public class FetchData {
10. public static void main(String[] args) {
11.
12. AnnotationConfiguration configuration=new AnnotationConfiguration();
13. configuration.configure("hibernate.cfg.xml");
14. SessionFactory sFactory=configuration.buildSessionFactory();
15.
Session session=sFactory.openSession();
16.

33
17.
//Hibernate Named Query
18.
Query query = session.getNamedQuery("findEmployeeByName");
19.
query.setString("name", "amit");
20.
21.
List<Employee> employees=query.list();
22.
23.
Iterator<Employee> itr=employees.iterator();
24.
while(itr.hasNext()){
25.
Employee e=itr.next();
26.
System.out.println(e);
27.
}
28.
29.
session.close();
30.
31. }
32. }
Hibernate Named Query by mapping file
If want to define named query by mapping file, you need to use query element of
hibernate-mapping to define the named query.
In such case, you need to create hbm file that defines the named query. Other resources
are same as given in the above example except Persistent class Employee.java where you
don't need to use any annotation and hibernate.cfg.xml file where you need to specify
mapping resource of the hbm file.
The hbm file should be like this:
emp.hbm.xml
1. <?xml version='1.0' encoding='UTF-8'?>
2. <!DOCTYPE hibernate-mapping PUBLIC
3.
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
4.
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
5.
6. <hibernate-mapping>
7. <class name="com.javatpoint.Employee" table="em">
8. <id name="id">
9. <generator class="native"></generator>
10. </id>
11. <property name="name"></property>
12. <property name="job"></property>
13. <property name="salary"></property>
14. </class>
15.
16. <query name="findEmployeeByName">
17. <![CDATA[from Employee e where e.name = :name]]>
18. </query>
19.
20. </hibernate-mapping>

34
The persistent class should be like this:
Employee.java
1. package com.javatpoint;
2. public class Employee {
3.
int id;
4.
String name;
5.
int salary;
6.
String job;
7.
//getters and setters
8. }
Now include the mapping resource in the hbm file as:
hibernate.cfg.xml
1. <mapping resource="emp.hbm.xml"/>

Vous aimerez peut-être aussi