Hibernate Interview Questions
Hibernate Interview Questions
Hibernate Interview Questions
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:
Programmatic configuration
XML configuration (hibernate.cfg.xml)
Session interface
SessionFactory interface
Configuration interface
Transaction interface
Query and Criteria interfaces
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
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>
5
load() vs. get() :load()
get()
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.
Example:
order collection
9
Hibernate Vs. JDBC :JDBC
Hibernate
10
done manually.
cost.
Bag
Set
List
Array
Map
11
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:
EJB 3.0
13
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.
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.
RDBMS
Dialect
org.hibernate.dialect.Oracle9iDialect
Oracle10g
org.hibernate.dialect.Oracle10gDialect
MySQL
org.hibernate.dialect.MySQLDialect
org.hibernate.dialect.DB2Dialect
DB2 AS/400
org.hibernate.dialect.DB2400Dialect
DB2 OS390
org.hibernate.dialect.DB2390Dialect
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:
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.
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
23
4.
5.
6.
7.
8.
<defaultCache
maxElementsInMemory="100"
eternal="true"/>
</ehcache>
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.
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();
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.
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.
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.
31
3.
4.
5.
6.
7.
}
8. )
@NamedQuery(
name = "findEmployeeByName",
query = "from Employee e where e.name = :name"
)
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"/>