In this article, we will discuss frequently asked Hibernate Interview Questions and Answers
1. What is Hibernate ?
Hibernate is an ORM(Object Relational Mapping) framework that maps POJOs to tables in relational database.
The mapping is done through a xml configuration file or through annotations.
2. What are some advantages of Hibernate ?
- Hibernate takes care of mapping Java objects to tables using XML files or annotations without having to write any code.
- Hibernate provides simple apis to store & access data from the database.
- Supports most of relational databases like DB2, Sybase, Oracle etc. Database changes can be managed as we only to change the XML.
- It manages complex table associations and provides different fetching strategies to access the data.
3. What is ORM framework ?
Object Relational Mapping frameworks like Hibernate, IBatis etc provide mapping between code and tables.
This helps productivity as the developers can focus on their business logic rather than coding for database connectivity.
It provides improved performance through features like caching, lazy loading, eager loading etc.
The framework helps removing application’s dependency on particular database. The application code remains portable across databases.
4. What is Hibernate configuration file?
The Hibernate configuration file name is hibernate.cfg.xml.
It is required to :
– Define database properties like server name, id , pwd etc
– It also contains the reference for the mapping files which contains details of classes that are persisted and their relationships.
5. How to print the sql queries in development environment in Hibernate?
We can set the config property hibernate.show_sql to true to print the sql queries.
6. What are the different persistence states of Objects in Hibernate ?
Objects can be in 3 states of persistence :
Transient State
Object persists in memory and database has no knowledge of the object yet.
To persist this type ob object, the session must save it.
Persistent State
Objects exist in db and managed by hibernate
If a property changes in a persistent object, hivernate updates the database for the same.
Detached State
Object exists in db, but hibernate no longer has a connection to it.
It is a persistent object, for which session has been closed.
7. What is SessionFactory in Hibernate ?
SessionFactory object is created using a configuration object which in-turn is created from the supplied configuration file.
SessionFactory is a threadsafe object.
Its considered a heavyweight object, hence created during app startup.
Application should only have a single SessionFactory instance. Separate SF objects are required for connecting to multiple databases.
Typically there is only one Session Factory for the whole application.
8. What is Session in Hibernate ?
Session represents a conversation between the application and database.
It is used to establish to connection to database.
It is lightweight and designed to be instantiated each time a connection is needed to the db.
Persistent objects are created and read using session.
Session holds a mandatory first level cache of persistent objects.
Session object is obtained from SessionFactory.
9. What is a Transaction Object ?
A tranaction is a unit of work guaranteed to behave as if you have exclusive access to the db.
A transaction can be started, commited ot rolled back.
Transactions are handled by an underlying TransactionManager.
10. What are different types of caches in Hibernate ?
Hibernate uses two different type of caches for objects: first-level cache and second-level cache.
First level of cache is associated with Session object, while second-level of cache is associated with the SessionFactory object.
By default, Hibernate uses first-level of cache on a per-transaction basis. Hibernate mainly use this cache to reduce the number of SQL queries it needs to generate within a given transaction.
11. What is the difference between get() and load() methods in Hibernate ?
load():
– Use load() method only when you are sure that object you want to read already exists.
– If unique Id of an object does not exists in database then load() method will throw an exception.
– load() method return proxy object default and database won’t be hit until the proxy is first invoked.
get():
– Use get() method when you are not sure about the object existence in the database.
– If object does not exists in the database, the get() method will return null.
– get() method will hit database immediately.
12. When to use merge() and when to use update() method in Hibernate ?
Use update() method when you are sure that 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.
13. What is Hibernate Query Language (HQL) ? Explain how to perform DML operations using HQL.
HQL provides an alternative to SQL to query the tables.
HQL adds a layer of abstraction for the developers. It uses Class name in place of Table name and Property name in place of column name.So, the program doesn’t need to change if the underlying database structure changes.
The HQL queries ate translated to SQL queries by Hibernate.
See below for syntax of Select, Update and Insert operations.
Select
—- ——-
Query query = session.createQuery(“from Employee where empid = :empid”);
query.setParameter(empid, “123”);
List empList = query.list();
Query query = session.createQuery(“from Employee where empid = ?”);
query.setParameter(0, “123”); //can also use setString() or setProperties(<object>)
List empList = query.list();
Update
—– —-
Query query = session.createQuery(“Update Employee set empname = “:empname” where empid=:empid”);
query.setParameter(empname, “abc”);
query.setParameter(empid, “123”);
int result = query.executeUpdate();
Insert
—- —
insert into tablename values(…) is not supported. Inserting into a table by selecting values from another table is supported.
Query query = session.createQuery(“Insert into employee(empid, empname) select empid,empname from back_emp”);
int result = query.executeUpdate();
14. How to find max salary from the employee table using HQL ?
We can use aggregate methods for such queries:
String hql = "select max(e.salary) from Employee e";
Query query = session.createQuery(hql);
int max = (int) query.uniqueResult();
15. What is Criteria api ? What are the advantages and disadvantages of it ?
Hibernate Session has createCriteria() method to restrict the data we get back from the database.
Criteria api provides an Object Oriented and elegant approach compared to HQL.
Here an example of how to use criteria to select data from a table.
Criteria criteria = session.createCriteria(Employee.class);
criteria.list();
We can also use Restrictions to restrict the results as show below :
Criteria criteria = session.createCriteria(Employee.class);
criteria.add(Restrictions.eq("emp_id", "123"));
criteria.list();
We can also use other Restrictions methods like gt(greater than), lt(less than) etc :
Criteria criteria = session.createCriteria(Employee.class);
criteria.add(Restrictions.gt("salary", 50000));
criteria.list();
Lets use the Criteria api to order the results :
Criteria criteria = session.createCriteria(Employee.class);
criteria.add(Restrictions.gt("salary", 50000));
criteria.addOrder(Order.asc(“name”));
criteria.list();
Disadvantages of Criteria:
– Query scattered across code.
– Can’t control the query generated by hibernate.
16. How to do pagination in Hibernate using Criteria api ?
For pagination, maxresults and first result need to be set as follows :
criteria.setMaxResults(10);
criteria.setFirstResult(1);
17. What are Named Queries ? Explain how to use them .
Named queries are easier to maintain as they are added in the mapping xml files.
Query names should be unique.
Here is an example of a named query:
<query name=”query1”>
<![CDATA[ from employee where emp_id = :emp_id ]]>
</query>
CDATA blocks avoids warning because of > or < symbol.
Here is how the Named query can be invoked in code:
Query query = session.getNamedQuery(“query1”);
query.setString(emp_id, “123”);
query.list();
18. What are Native Queries in Hibernate ?
Native Queries can be added similar to Named Queries. However, the query added is database specific.
Normally, native queries are used when a query is already optimized by database developers and dbas and should be used as is in the application rather than depending on Hibernate to generate and optimize it.
Here is an example:
<sql-query name=”query1”>
<![CDATA[ select * from employee where emp_id = :emp_id ]]
</sql_query>
© 2015 – 2018, https:. All rights reserved. On republishing this post, you must provide link to original post
#