Google News
logo
Java Hibernates Interview Questions
Hibernate : Hibernate is one of the most popular Java frameworks that simplify the development of Java application to interact with the database. It is an Object-relational mapping (ORM) tool. Hibernate also provides a reference implementation of Java API.
 
It is referred as a framework which comes with an abstraction layer and also handles the implementations internally. The implementations include tasks like writing a query for CRUD operations or establishing a connection with the databases, etc.
 
Hibernate develops persistence logic, which stores and processes the data for longer use. It is a lightweight tool and most importantly open-sourced which gives it an edge over other frameworks.
Object-relational mapping or ORM is the programming technique to map application domain model objects to the relational database tables. Hibernate is java based ORM tool that provides framework for mapping application domain objects to the relational database tables and vice versa.
 
Hibernate provides reference implementation of Java Persistence API, that makes it a great choice as ORM tool with benefits of loose coupling. We can use Hibernate persistence API for CRUD operations. Hibernate framework provide option to map plain old java objects to traditional database tables with the use of JPA annotations as well as XML based configuration.
An Object Relational Mapping (ORM) tool helps to simplify data creation, manipulation, and access by internally using Java API to interact with the databases. It’s a technique that maps objects stored in a database.
Clean Readable Code : Using hibernate, helps in eliminating a lot of JDBC API-based boiler-plate codes, thereby making the code look cleaner and readable.

HQL (Hibernate Query Language) : Hibernate provides HQL which is closer to Java and is object-oriented in nature. This helps in reducing the burden on developers for writing database independent queries. In JDBC, this is not the case. A developer has to know the database-specific codes.

Transaction Management : JDBC doesn't support implicit transaction management. It is upon the developer to write transaction management code using commit and rollback methods. Whereas, Hibernate implicity provides this feature.

Exception Handling : Hibernate wraps the JDBC exceptions and throws unchecked exceptions like JDBCException or HibernateException. This along with the built-in transaction management system helps developers to avoid writing multiple try-catch blocks to handle exceptions. In the case of JDBC, it throws a checked exception called SQLException thereby mandating the developer to write try-catch blocks to handle this exception at compile time.

Special Features : Hibernate supports OOPs features like inheritance, associations and also supports collections. These are not available in JDBC.
Hibernate core interfaces are :
 
* Configuration
* SessionFactory
* Session
* Criteria
* Query
* Transaction
Some of the databases supported by Hibernate are :
 
* DB2
* MySQL
* Oracle
* Sybase SQL Server
* Informix Dynamic Server
* HSQL
* PostgreSQL
* FrontBase
Some of the important advantages of Hibernate framework over JDBC are :
 
* Hibernate removes a lot of boiler-plate code that comes with JDBC API, the code looks more cleaner and readable.
* Hibernate supports inheritance, associations and collections. These features are not present with JDBC API.
* Hibernate implicitly provides transaction management, in fact most of the queries can’t be executed outside transaction. In JDBC API, we need to write code for transaction management using commit and rollback. Read more at JDBC Transaction Management.
* JDBC API throws SQLException that is a checked exception, so we need to write a lot of try-catch block code. Most of the times it’s redundant in every JDBC call and used for transaction management. Hibernate wraps JDBC exceptions and throw JDBCException or HibernateException un-checked exception, so we don’t need to write code to handle it. Hibernate built-in transaction management removes the usage of try-catch blocks.
* Hibernate Query Language (HQL) is more object oriented and close to java programming language. For JDBC, we need to write native sql queries.
* Hibernate supports caching that is better for performance, JDBC queries are not cached hence performance is low.
* Hibernate provide option through which we can create database tables too, for JDBC tables must exist in the database.
* Hibernate configuration helps us in using JDBC like connection as well as JNDI DataSource for connection pool. This is very important feature in enterprise application and completely missing in JDBC API.
* Hibernate supports JPA annotations, so code is independent of implementation and easily replaceable with other ORM tools. JDBC code is very tightly coupled with the application.
* Hibernate is an ORM tool.
* Hibernate uses Hibernate Query Language(HQL) which makes it database-independent.
* It supports auto DDL operations.
* This Java framework also has an Auto Primary Key Generation support.
* Supports cache memory.
* Exception handling is not mandatory in the case of Hibernate.
Some of the important interfaces of Hibernate framework are :
 
SessionFactory (org.hibernate.SessionFactory) : SessionFactory is an immutable thread-safe cache of compiled mappings for a single database. We need to initialize SessionFactory once and then we can cache and reuse it. SessionFactory instance is used to get the Session objects for database operations.

Session (org.hibernate.Session) : Session is a single-threaded, short-lived object representing a conversation between the application and the persistent store. It wraps JDBC java.sql.Connection and works as a factory for org.hibernate.Transaction. We should open session only when it’s required and close it as soon as we are done using it. Session object is the interface between java application code and hibernate framework and provide methods for CRUD operations.

Transaction (org.hibernate.Transaction) :  Transaction is a single-threaded, short-lived object used by the application to specify atomic units of work. It abstracts the application from the underlying JDBC or JTA transaction. A org.hibernate.Session might span multiple org.hibernate.Transaction in some cases.
Hibernate configuration file contains database specific configurations and used to initialize SessionFactory. We provide database credentials or JNDI resource information in the hibernate configuration xml file. Some other important parts of hibernate configuration file is Dialect information, so that hibernate knows the database type and mapping file or class details.
Hibernate mapping file is used to define the entity bean fields and database table column mappings. We know that JPA annotations can be used for mapping but sometimes XML mapping file comes handy when we are using third party classes and we can’t use annotations.
Session interface is primarily used by hibernate application. Session is light weight,short lived objects which are inexpensive to create and destroy. It allows you to create query objects to retrieve persistent objects.It wraps JDBC connection Factory for Transaction.It holds a mandatory (first-level) cache of persistent objects, used when navigating the object graph or looking up objects by identifier .
13 .
HQL stands for Hibernate Query Language, a powerful object-oriented language independent of the database. It’s like SQL, except that it uses objects instead of table names. HQL is a very simple, efficient, and flexible query language used to do various operations on a relational database without the need for complex database queries.
Hibernate's four ORM levels are :
 
* Full Object Mapping
* Light Object Mapping
* Medium Object Mapping
* Pure Relational

After looking into some of the basic Hibernate interview questions, let us level up and look into the intermediate level questions.
The automatic dirty checking feature of Hibernate, calls update statement automatically on the objects that are modified in a transaction.
 
Let's understand it by the example given below :
...  
SessionFactory factory = cfg.buildSessionFactory();  
Session session1 = factory.openSession();  
Transaction tx=session2.beginTransaction();  
   
Employee e1 = (Employee) session1.get(Employee.class, Integer.valueOf(101));  
   
e1.setSalary(90000);  
   
tx.commit();  
session1.close();
Concurrency strategies are mediators responsible for storing and retrieving cached items. When enabling a second-level cache, the developer must decide which cache concurrency to implement for each persistent class and collection.
 
The concurrency strategies are :
 
Non-strict-Read-Write : This strategy works with data that can be altered and can tolerate a small chance of stale data. This strategy offers no guarantee of consistency between the database and the cache.

Read-Only : This strategy works best with data that can’t be changed, and consequently, is only used to reference data.

Transactional : This strategy is used primarily for read-mostly data in cases where it’s essential to prevent stale data in concurrent transactions, in those rare instances of an update.

Read-Write : This strategy is like the transactional strategy.
The process of Hibernate tuning is designed to optimize Hibernate applications’ performance. The three strategies are :
 
* SQL Optimization
* Session Management
* Data Caching
* In this association, one object can be associated with multiple objects.

* The One-to-Many mapping is implemented using a Set Java collection that does not have any redundant element.

* A One-to-Many element of the set element indicates the relation of one object to multiple objects.
* This association is the common type of association where one object can be associated with multiple objects.

* And Many-to-one element defines the Many-to-One association.To the defined variable, a name attribute is set in the parent class and column attribute sets the column name in the parent table.
Many-to-Many mapping requires an entity attribute and a @ManyToMany annotation. It can either be unidirectional and bidirectional. In Unidirectional, the attributes model the association and you can use it to navigate it in your domain model or JPQL queries. The annotation tells Hibernate to map a Many-to-Many association. The bidirectional relationship, mapping allows you to navigate the association in both directions. 
* It is similar to the many-to-one association and the difference lies in the column that will be set as a unique one.The many-to-one element is used to define one-to-one association.

* To the defined variable a name attribute is set in the parent class and the column attribute is used to set column name in the parent table, which is unique so that only one object gets associated with another.
To create a session factory in hibernate, an object of configuration is created first which refers to the path of configuration file and then for that configuration, session factory is created as given in the example below :
Configuration config = new Configuration();
config.addResource("myinstance/configuration.hbm.xml");
config.setProperties( System.getProperties() );
SessionFactory sessions = config.buildSessionFactory();
* POJOs( Plain Old Java Objects) are java beans with proper getter and setter methods for each and every properties.

* Use of POJOs instead of simple java classes results in an efficient and well constructed code.
Session.save() method saves a record only if it’s unique with respect to its primary key and will fail to insert if primary key already exists in the table.

Session.saveOrUpdate() method inserts a new record if primary key is unique and will update an existing record if primary key exists in the table already.
The hibernate Session interface provides createCriteria() method, which can be used to create a criteria object that returns instances of the persistence object’s class when your application executes a criteria query.
 
Example of criteria :
 
Criteria cr = session.createCriteria(Freetimelearning.class);
 
List results = cr.list();
It is usually created only once during application initialization. It represents a configuration or properties file required by the Hibernate.
 
The Configuration object provides two keys 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.
The entity manager interface provides a method called create native career avoid this method returns an implementation of equilibria interface which is same as if you call the create query method to create equity the code to a JPA.
 
Ex :
Call EntityManager.createNativeQuery(String query)method.

Query q=em.createNativeQuery(“SELECT a.firstname,a.lastname”+”FROM Author a”);

Create hibernate.cfg.xml configuration file 

Create Employee.hbm.xml mapping file 

Create Employee.java source file and compile it.

Create ManageEmployee.java source file and compile it.

Execute ManageEmployee binary to run the program.
For connecting hibernate application with database then we must specify the SQLDialect, which contain the mapping between java language data type and database datatypes. There are many dialect classes for defining the RDBMS.
 
Hibernate uses dialect configuration to know which database you are using so that, it can switch to the database-specific SQL generator. Hibernate generates all your entity mappings and hibernate queries to Specific database query and uses JDBC to execute them.
To enable second-level cache we need to follow some points regarding cache, First level cache enabled by default. Whenever we are loading any object from the database, Then hibernate verify whether that object is available in the local cache memory of that particular session, means first level cache, if not available then hibernate verify whether the object is available in global cache or factory cache second-level cache, if not available then hibernate will hit the database and loads the object from there, and then first stores in the local cache of the session, the first level then in the global cache second-level cache.
 
Ex :
Session s2=sf.openSession();
s2.beginTransaction();
a=(user)s2.get(user.class,102);
System.out.println(a);
s2.getTransaction().commit();
s2.close();
The return type of the Session.save() method is java.io.Serializable. It returns the newly generated identifier id value as a serializable object. While return type of the session.persist() method does not return anything. 
 
Syntax :
Serializable ser=session.save(object);
No, the session is not a thread-safe object, many threads cant access it simultaneously. In other words, you cannot share it between threads.
Lazy loading is mainly used for improving the application performance by helping to load the child objects on demand.
 
It is to be noted that, since Hibernate 3 version, this feature has been enabled by default. This signifies that child objects are not loaded until the parent gets loaded.
Immutable class in hibernate creation could be in the following way. If we are using the XML form of configuration, then a class can be made immutable by markingmutable=false. The default value is true there which indicating that the class was not created by default.
 
In the case of using annotations, immutable classes in hibernate can also be created by using @Immutable annotation.
SQL injection attack is a serious vulnerability in terms of web security wherein an attacker can interfere with the queries made by an application/website to its database thereby allowing the attacker to view sensitive data which are generally irretrievable. It can also give the attacker to modify/ remove the data resulting in damages to the application behavior.
 
Hibernate does not provide immunity to SQL Injection. However, following good practices avoids SQL injection attacks. It is always advisable to follow any of the below options :
 
* Incorporate Prepared Statements that use Parameterized Queries.
* Use Stored Procedures.
* Ensure data sanity by doing input validation.
These are the methods to get data from the database. The primary differences between get and load in Hibernate are given below :

get() :
* This method gets the data from the database as soon as it is called.
* The database is hit every time the method is called.
* The method returns null if the object is not found.
* This method should be used if we are unsure about the existence of data in the database.
 
load() :
* This method returns a proxy object and loads the data only when it is required.
* The database is hit only when it is really needed and this is called Lazy Loading which makes the method better.
* The method throws ObjectNotFoundException if the object is not found.
* This method is to be used when we know for sure that the data is present in the database.
session.lock() method is used to reattach a detached object to the session. session.lock() method does not check for any data synchronization between the database and the object in the persistence context and hence this reattachment might lead to loss of data synchronization.
setMaxResults() the function works similar to LIMIT in SQL. Here, we set the maximum number of rows that we want to be returned. This method is implemented by all database drivers.
 
setFetchSize() works for optimizing how Hibernate sends the result to the caller for example: are the results buffered, are they sent in different size chunks, etc. This method is not implemented by all the database drivers.
Yes, it does. Hibernate provides the createSQLQuery() method to let a developer call the native SQL statement directly and returns a Query object.
 
Consider the example where you want to get employee data with the full name “Hibernate”. We don't want to use HQL-based features, instead, we want to write our own SQL queries. In this case, the code would be:
Query query = session.createSQLQuery( "select * from interviewbit_employee ibe where ibe.fullName = :fullName")
                   .addEntity(InterviewBitEmployee.class)
                   .setParameter("fullName", "Hibernate"); //named parameters
List result = query.list();
Alternatively, native queries can also be supported when using NamedQueries.
This getCurrentSession() method returns the session bound to the context and for this to work, you need to configure it in Hibernate configuration file. Since this session object belongs to the context of Hibernate, it is okay if you don’t close it. Once the SessionFactory is closed, this session object gets closed.

openSession() method helps in opening a new session. You should close this session object once you are done with all the database operations. And also, you should open a new session for each request in a multi-threaded environment.
An entity bean instance can exist is one of the three states.
 
Transient : When an object is never persisted or associated with any session, it’s in transient state. Transient instances may be made persistent by calling save(), persist() or saveOrUpdate(). Persistent instances may be made transient by calling delete().

Persistent : When an object is associated with a unique session, it’s in persistent state. Any instance returned by a get() or load() method is persistent.

Detached : When an object is previously persistent but not associated with any session, it’s in detached state. Detached instances may be made persistent by calling update(), saveOrUpdate(), lock() or replicate(). The state of a transient or detached instance may also be made persistent as a new persistent instance by calling merge().
Hibernate merge can be used to update existing values, however this method create a copy from the passed entity object and return it. The returned object is part of persistent context and tracked for any changes, passed object is not tracked.
Hibernate uses Reflection API to create instance of Entity beans, usually when you call get() or load() methods. The method Class.newInstance() is used for this and it requires no-args constructor. So if you won’t have no-args constructor in entity beans, hibernate will fail to instantiate it and you will get HibernateException.
There are various ways to implement joins in hibernate.
 
* Using associations such as one-to-one, one-to-many etc.
* Using JOIN in the HQL query. There is another form “join fetch” to load associated data simultaneously, no lazy loading.
* We can fire native sql query and use join keyword.
Hibernate implements a cache region for queries resultset that integrates closely with the hibernate second-level cache.
 
This is an optional feature and requires additional steps in code. This is only useful for queries that are run frequently with the same parameters. First of all we need to configure below property in hibernate configuration file.
<property name="hibernate.cache.use_query_cache">true</property>
And in code, we need to use setCacheable(true) method of Query, quick example looks like below.
Query query = session.createQuery("from Employee");
query.setCacheable(true);
query.setCacheRegion("ALL_EMP");
Hibernate provides Criteria API that is more object oriented for querying the database and getting results. We can't use Criteria to run update or delete queries or any DDL statements. It’s only used to fetch the results from the database using more object oriented approach.
 
Some of the common usage of Criteria API are :
 
* Criteria API provides Projection that we can use for aggregate functions such as sum(), min(), max() etc.
* Criteria API can be used with ProjectionList to fetch selected columns only.
* Criteria API can be used for join queries by joining multiple tables, useful methods are createAlias(), setFetchMode() and setProjection()
* Criteria API can be used for fetching results with conditions, useful methods are add() where we can add Restrictions.
* Criteria API provides addOrder() method that we can use for ordering the results.
We can set below property for hibernate configuration to log SQL queries.
<property name="hibernate.show_sql">true</property>
However we should use it only in Development or Testing environment and turn it off in production environment.
Transaction management is very easy in hibernate because most of the operations are not permitted outside of a transaction. So after getting the session from SessionFactory, we can call session beginTransaction() to start the transaction. This method returns the Transaction reference that we can use later on to either commit or rollback the transaction.
 
Overall hibernate transaction management is better than JDBC transaction management because we don’t need to rely on exceptions for rollback. Any exception thrown by session methods automatically rollback the transaction.
Hibernate 4 uses JBoss logging rather than slf4j used in earlier versions. For log4j configuration, we need to follow below steps.
 
* Add log4j dependencies for maven project, if not maven then add corresponding jar files.

* Create log4j.xml configuration file or log4j.properties file and keep it in the classpath. You can keep file name whatever you want because we will load it in next step.

* For standalone projects, use static block to configure log4j using DOMConfigurator or PropertyConfigurator. For web applications, you can use ServletContextListener to configure it.

* That’s it, our setup is ready. Create org.apache.log4j.Logger instance in the java classes and start logging.
For web applications, it’s always best to allow servlet container to manage the connection pool. That’s why we define JNDI resource for DataSource and we can use it in the web application. It’s very easy to use in Hibernate, all we need is to remove all the database specific properties and use below property to provide the JNDI DataSource name.
<property name="hibernate.connection.datasource">java:comp/env/jdbc/MyLocalDB</property>
It may exist in one of the following 3 states :
 
Transient : This is not associated with the Session and has no representation in the database.
Persistent : You can make a transient instance persistent by associating it with a Session.
Detached : If you close the Hibernate Session, the persistent instance will become a detached instance.
* Hibernate uses a proxy object in order to support Lazy loading.
* When you try loading data from tables, Hibernate doesn’t load all the mapped objects.
* After you reference a child object through getter methods, if the linked entity is not present in the session cache, then the proxy code will be entered to the database and load the linked object.
* It uses Java assist to effectively and dynamically generate sub-classed implementations of your entity objects.
Yes, you can declare entity class as final but it is not considered as a good practice because hibernate uses proxy pattern for lazy initialisation, If you declare it as final then hibernate won’t be able to create sub class and won’t be able to use proxy pattern, so it will limit performance and improvement options.
There are three ways to disable the cache :
 
* By setting hibernate. cache. use_second_level_cache property to false
* By using CACHEMODE.IGNORE
* Using a cache provider such as org.hibernate.cache.NoCacheProvider
* It is used to define specific mappings from Java classes to database tables.
* It is used to define the mapping of unique ID attribute in class to the primary key of the database table.
* It is used to generate the primary key values automatically.
* It is used to map a Java class property to a column in the database table.
* It is used to map a java.util.set, java.util.Sortedset property in hibernate.
* It is used to map a java.util.List property in hibernate.
* It is used to map a java.util.Collection property in hibernate.
* It is used to map a java.util.Map property in hibernate.
Hibernate Dialect is used to specify the type of database we are going to use. Hibernate requires this to know in advance so it is able to generate appropriate type of SQL statements based on database type.
Java Applications and components are managed in hibernate by a standard API called JMX API. JMX provides tools for development of efficient and robust distributed, web based solutions.
Yes, hibernate fully supports polymorphism. Polymorphism queries and polymorphism associations are supported in all mapping strategies of hibernate.
General hibernate flow involving RDBMS is as follows :

* Load configuration file and create object of configuration class.
* Using configuration object, create sessionFactory object.
* From sessionFactory, get one session.
* Create HQL query.
* Execute HQL query and get the results. Results will be in the form of a list.
Some of the most common disadvantages of hibernate are performance cost, does not allow too many inserts, more complex joins, poor performance in batch processing, learning curve, not good for a small project.
Hibernate is good or bad depending on the kind of hard disk you have. During hibernate, the PC actions are frozen, and the state is safely stored on the hard disk in an enormous hibernation file, which is called hiberfil.sys in Windows systems.
Hibernate is not essentially bad for SSD. We can just say, it is not that useful with an SSD. Hibernate enables you to start your work again after putting it to sleep. Hibernate helps in saving everything to disk from memory.
A concurrency strategy is a mediator which responsible for storing items of data in the cache and retrieving them from the cache. If you are going to enable a second-level cache, you will have to decide, for each persistent class and collection, which cache concurrency strategy to use.
 
Transactional : Use this strategy for read-mostly data where it is critical to prevent stale data in concurrent transactions,in the rare case of an update.
 
Read-write : Again use this strategy for read-mostly data where it is critical to prevent stale data in concurrent transactions,in the rare case of an update.
 
Nonstrict-read-write : This strategy makes no guarantee of consistency between the cache and the database. Use this strategy if data hardly ever changes and a small likelihood of stale data is not of critical concern.
 
Read-only : A concurrency strategy suitable for data which never changes. Use it for reference data only.
Hibernate also implements a cache for query resultsets that integrates closely with the second-level cache.
 
This is an optional feature and requires two additional physical cache regions that hold the cached query results and the timestamps when a table was last updated. This is only useful for queries that are run frequently with the same parameters.
Session.beginTransaction method begins a unit of work and returns the associated Transaction object.
steps to create hibernate projects in eclipse
 
* First, create the java project in eclipse
* Download the hibernate from a website then it shows to your download hibernate library then hit into the hibernate after download, add jar files to hibernate.
* Add MySQL JDBC driver to file
* Then, Create a Persistent class with mapping information
* After creating persistence class then again create  the Hibernate Configuration file
* Create a Utility class for initializing the SessionFactory
* Create Example code to load the data from Database
* After doing all the above points right-click on mouse u see run option then hit on the RUN
* Run the Example.