Hibernate interview Questions

Hibernate interview Questions

Hibernate is one of the most widely used ORM tool for Java applications. It’s used a lot in enterprise applications for database operations.
Whether you are fresher or experienced, having good knowledge or Hibernate ORM tool helps in cracking interview. Here I am providing important hibernate interview questionswith answers to help you brush up your knowledge and impress your interviewer. Just like other interview questions posts, chances are that I will be adding more questions to this list in future, so you might want to bookmark it for future reference.
Recently I have written a lot of posts on hibernate, most of them contains complete downloadable projects. I will provide reference to them as and when needed and you can go through them to refresh your knowledge.
Here is my list of Hibernate interview question, which I have collected from friends and colleagues. Hibernate is a popular Object Relational Mapping framework and good knowledge of advantages offered by Hibernate along with Hibernate Session API is key to do well in any Hibernate Interview.

Q: What is Hibernate?
A: Synonym of Hibernate is Winter.  It means Spend the winter in a dormant state.
As a technology Hibernate is a open source, free Java package that makes it easy to work with relational databases. It 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.

Q: What is ORM?
A: ORM stands for Object/Relational mapping. It is the programmed and mapping of objects in a Java application in to the tables of a relational database using the metadata that describes the mapping between the objects and the database. It works by transforming the data from one representation to another.
We are familiar with Model/Pojo class and Relational Database. Here Object means Mode/Pojo class and Relational means the databases. By hbm.xml file we represent the mapping between Object and Relational databases.

Q: What does an ORM solution comprises of?
A: Hibernate should have an language or API for performing basic CRUD (Create, Read, Update, Delete) operations on objects of persistent classes where persistent means POJO classes that you create that represent the table in database to keep the state of object alive.
It should have a language or an API for specifying queries that refer to the classes and the properties of classes an ability for specifying mapping metadata.
It should have a technique for ORM implementation to interact with transactional objects to perform lazy association fetching, dirty checking, and other optimization functions.

Q: What are the different levels of ORM quality?
A: Four levels defined for ORM quality:
    Pure relational
    Light object mapping
    Medium object mapping
    Full object mapping

Pure relational:
The entire application, including the user interface, designed around the relational model and SQL based relational operations.
Light object mapping :
The entities are represented as classes that are mapped manually to the relational tables. The code is hidden from the business logic using specific design patterns. This approach is successful for applications with a less number of entities, or applications with common, metadata-driven data models.
Medium object mapping:
The application is designed around an object model. The SQL code is generated at build time. And the associations between objects are supported by the persistence mechanism, and queries are specified using an object-oriented expression language. This is best suited for medium-sized applications with some complex transactions.
Full object mapping:
Full object mapping supports sophisticated object modeling: inheritance, polymorphism, composition and persistence. The persistence layer implements transparent persistence. Persistent classes do not inherit any special base class or have to implement a special interface. Efficient fetching strategies and caching strategies are implemented transparently to the application.

Q: What is a pure relational ORM?
A: The entire application including the user interface is designed around the relational model and SQL based relational operations where Model and Database will be mapped through hbm.xml configuration files and can execute SQL operations using Model Objects.

Q: Why do you need ORM tools like hibernate?
A: The main advantage of ORM like hibernate is that it shields developers from messy SQL. Apart from this, ORM provides following benefits:
-> mproved productivity
* High-level object-oriented API
* Less Java code to write
* No SQL to write

-> Improved performance
* Sophisticated caching
* Eager loading

-> Improved maintainability
* A lot less code to write

-> Improved portability
* ORM framework generates database-specific SQL for you

Q: What is a meant by light object mapping?
A: The entities are represented as classes that are mapped manually to the relational tables. The code is hidden from the business logic using specific design patterns. This approach is successful for applications with a less number of entities, or applications with common, metadata-driven data models. This approach is most known to all.

Q: What is a meant by medium object mapping?
A: The application is designed around an object model. The SQL code is generated at build time. And the associations between objects are supported by the persistence mechanism, and queries are specified using an object-oriented expression language. This is best suited for medium-sized applications with some complex transactions. Used when the mapping exceeds 25 different database products at a time.

Q: What is meant by full object mapping?
A: Full object mapping supports sophisticated object modeling: composition, inheritance, polymorphism and persistence. The persistence layer implements transparent persistence; persistent classes do not inherit any special base class or have to implement a special interface. Efficient fetching strategies and caching strategies are implemented transparently to the application.

Q: What are the benefits of ORM and Hibernate?
A: There are many benefits from these. Out of which the following are the most important one.
Productivity : Hibernate reduces the burden of developer by providing much of the functionality and let the developer to concentrate on business logic.
Maintainability :As hibernate provides most of the functionality, the LOC for the application will be reduced and it is easy to maintain. By automated object/relational persistence it even reduces the LOC.
Performance : Hand-coded persistence provided greater performance than automated one. But this is not true all the times. But in hibernate, it provides more optimization that works all the time there by increasing the performance. If it is automated persistence then it still increases the performance.
Vendor independence : Irrespective of the different types of databases that are there, hibernate provides a much easier way to develop a cross platform application.

Q: What the Core interfaces are of hibernate framework?
A: There are many benefits from these. Out of which the following are the most important one.
Session Interface : This is the primary interface used by hibernate applications. The instances of this interface are lightweight and are inexpensive to create and destroy. Hibernate sessions are not thread safe.
SessionFactory Interface : This is a factory that delivers the session objects to hibernate application. Generally there will be a single SessionFactory for the whole application and it will be shared among all the application threads.
Configuration Interface : This interface is used to configure and bootstrap hibernate. The instance of this interface is used by the application in order to specify the location of hibernate specific mapping documents.
Transaction Interface : This is an optional interface but the above three interfaces are mandatory in each and every application. This interface abstracts the code from any kind of transaction implementations such as JDBC transaction, JTA transaction.
Query and Criteria Interface : This interface allows the user to perform queries and also control the flow of the query execution.

Q: What are Callback interfaces?
A: These interfaces are used in the application to receive a notification when some object events occur. Like when an object is loaded, saved or deleted. There is no need to implement callbacks in hibernate applications, but they're useful for implementing certain kinds of generic functionality.

Q: What should SessionFactory be placed so that it can be easily accessed?
A: As far as it is compared to J2EE environment, if the SessionFactory is placed in JNDI then it can be easily accessed and shared between different threads and various components that are hibernate aware. You can set the SessionFactory to a JNDI by configuring a property hibernate.session_factory_name in the hibernate.properties file.

Q: What are POJOs?
A: POJO stands for plain old java objects. These are just basic JavaBeans that have defined setter and getter methods for all the properties that are there in that bean. Besides they can also have some business logic related to that property. Hibernate applications works efficiently with POJOs rather then simple java classes.
Use setter when you need to mutate/set some values in bean object.
Use getter when you need to get values from bean.
In Hibernate, after creating the bean object you should set values to bean and save or update bean object to session or after setting you can get values from bean if you want to fetch bean data.

Q: What is object/relational mapping metadata?
A: ORM tools require a metadata format for the application to specify the mapping between classes and tables, properties and columns, associations and foreign keys, Java types and SQL types. This information is called the object/relational mapping metadata. It defines the transformation between the different data type systems and relationship representations.

Q: What is HQL?
A: HQL stands for Hibernate Query Language. Hibernate allows the user to express queries in its own portable SQL extension and this is called as HQL. It also allows the user to express in native SQL.

Q: What are the most common methods of Hibernate configuration?
A: The most common methods of Hibernate configuration are:
* Programmatic configuration
* XML configuration (hibernate.cfg.xml)

Q: What are the important tags of hibernate.cfg.xml?
A: An Action Class is an adapter between the contents of an incoming HTTP request and the corresponding business logic that should be executed to process this request.

Q: What role does the Session interface play in Hibernate?
A: The Session interface is the primary interface used by Hibernate applications. It is a single-threaded, 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

Q: What role does the SessionFactory interface play in Hibernate?
A: The application obtains Session instances from a SessionFactory. There is typically a single SessionFactory for the whole application created 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();

Q: What is the general flow of Hibernate communication with RDBMS?
A: 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

Q: What is Hibernate Query Language (HQL)?
A: 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.

Q: How do you map Java Objects with Database tables?
A: * First we need to write Java domain objects (beans with setter and getter). The variables should be same as database columns.
* 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>

Q: What Does Hibernate Simplify?
A: 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

Q: What is the difference between load() and get()?
A: load() vs. get()
load() :-
Only use the load() method if you are sure that the object exists.
load() method will throw an exception if the unique id is not found in the database. load() just returns a proxy by default and database won't be hit until the proxy is first invoked.

get():- If you are not sure that the object exists, then use one of the get() methods.
get() method will return null if the unique id is not found in the database.
get() will hit the database immediately.

Q: What is the difference between and merge and update?
A: 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.

Q: How do you define sequence generated primary key in hibernate?
A: 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>

Q: Define cascade and inverse option in one-many mapping?
A: 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?

Q: What does it mean to be inverse?
A: It informs hibernate to ignore that end of the relationship. If the one-to-many was marked as inverse, hibernate would create a child->parent relationship (child.getParent). If the one-to-many was marked as non-inverse then a child->parent relationship would be created.

In Hibernate, only the “relationship owner" should maintain the relationship, and the “inverse" keyword is created to defines which side is the owner to maintain the relationship. However the “inverse" keyword itself is not verbose enough, I would suggest change the keyword to “relationship_owner“.

In short, inverse="true" means this is the relationship owner, and inverse="false" (default) means it’s not.
Suppose Stock is parent and StockDailyRecords is Child object.
Inverse keyword is applied in one to many relationship. Here’s the question, if save or update operation perform in “Stock" object, should it update the “stockDailyRecords" relationship?
1. inverse="true"
If inverse="true" in the set variable, it means “stock_daily_record" is the relationship owner, so Stock will NOT UPDATE the relationship.

2. inverse="false"
If inverse="false" (default) in the set variable, it means “stock" is the relationship owner, and Stock will UPDATE the relationship.
If keyword “inverse" is not define, the inverse = “false" will be used, which is

Q: What do you mean by Named - SQL query?
A: 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();

Q: How do you invoke Stored Procedures?
A: Ans.
<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>

Q: Explain Criteria API?
A: 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();

Q: Define HibernateTemplate?
A: 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.

Q: What are the benefits does HibernateTemplate provide?
A: 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.

Q: How do you switch between relational databases without code changes?
A: Using Hibernate SQL Dialects, we can switch databases. Hibernate will generate appropriate hql queries based on the dialect defined.

Q: If you want to see the Hibernate generated SQL statements on console, what should we do?
A: In Hibernate configuration file set as follows:
<property name=\"show_sql\">true</property>

Q: What are derived properties?
A: 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. People who read this also read:

Q: What is component mapping in Hibernate?
A: * 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

Q: What is the difference between sorted and ordered collection in hibernate?
A: sorted collection vs. order collection
sorted 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.
If your collection is not large, it will be more efficient way to sort it.

order collection :-
Order collection is sorting a collection by specifying the order-by clause for sorting this collection when retrieval.
If your collection is very large, it will be more efficient way to sort it .

Q: How will you configure Hibernate?
A: The configuration files hibernate.cfg.xml (or hibernate.properties) and mapping files *.hbm.xml are used by the Configuration class to create (i.e. configure and bootstrap hibernate) the SessionFactory, which in turn creates the Session instances. Session instances are the primary interface for the persistence service.

" hibernate.cfg.xml (alternatively can use hibernate.properties): These two files are used to configure the hibernate sevice (connection driver class, connection URL, connection username, connection password, dialect etc). If both files are present in the classpath then hibernate.cfg.xml file overrides the settings found in the hibernate.properties file.

" Mapping files (*.hbm.xml): These files are used to map persistent objects to a relational database. It is the best practice to store each object in an individual mapping file (i.e mapping file per class) because storing large number of persistent classes into one mapping file can be difficult to manage and maintain. The naming convention is to use the same name as the persistent (POJO) class name. For example Account.class will have a mapping file named Account.hbm.xml. Alternatively hibernate annotations can be used as part of your persistent class code instead of the *.hbm.xml files.

Q: What is a SessionFactory? Is it a thread-safe object?
A: SessionFactory is Hibernates concept of a single datastore and is threadsafe so that many threads can access it concurrently and request for sessions and immutable cache of compiled mappings for a single database. A SessionFactory is usually only built once at startup. SessionFactory should be wrapped in some kind of singleton so that it can be easily accessed in an application code.

Q: What is a Session? Can you share a session object between different threads?
A: Session is a light weight and a non-threadsafe object (No, you cannot share it between threads) that represents a single unit-of-work with the database. Sessions are opened by a SessionFactory and then are closed when all work is complete. Session is the primary interface for the persistence service. A session obtains a database connection lazily (i.e. only when required). To avoid creating too many sessions ThreadLocal class can be used as shown below to get the current session no matter how many times you make call to the currentSession() method.

Q: What are the benefits of detached objects?
A: Detached objects can be passed across layers all the way up to the presentation layer without having to use any DTOs (Data Transfer Objects). You can later on re-attach the detached objects to another session.

Q: What are the pros and cons of detached objects?
A: Pros:
" When long transactions are required due to user think-time, it is the best practice to break the long transaction up into two or more transactions. You can use detached objects from the first transaction to carry data all the way up to the presentation layer. These detached objects get modified outside a transaction and later on re-attached to a new transaction via another session.

Cons
" In general, working with detached objects is quite cumbersome, and better to not clutter up the session with them if possible. It is better to discard them and re-fetch them on subsequent requests. This approach is not only more portable but also more efficient because - the objects hang around in Hibernate's cache anyway.
" Also from pure rich domain driven design perspective it is recommended to use DTOs (DataTransferObjects) and DOs (DomainObjects) to maintain the separation between Service and UI tiers.

Q: How does Hibernate distinguish between transient (i.e. newly instantiated) and detached objects?
A: " Hibernate uses the version property, if there is one.
" If not uses the identifier value. No identifier value means a new object. This does work only for Hibernate managed surrogate keys. Does not work for natural keys and assigned (i.e. not managed by Hibernate) surrogate keys.
" Write your own strategy with Interceptor.isUnsaved().

Q: What is the difference between the session.get() method and the session.load() method?
A: Both the session.get(..) and session.load() methods create a persistent object by loading the required object from the database. But if there was not such object in the database then the method session.load(..) throws an exception whereas session.get(&) returns null.

Q: What is the difference between the session.update() method and the session.lock() method?
A: Both of these methods and saveOrUpdate() method are intended for reattaching a detached object. The session.lock() method simply reattaches the object to the session without checking or updating the database on the assumption that the database in sync with the detached object. It is the best practice to use either session.update(..) or session.saveOrUpdate(). Use session.lock() only if you are absolutely sure that the detached object is in sync with your detached object or if it does not matter because you will be overwriting all the columns that would have changed later on within the same transaction.
Note: When you reattach detached objects you need to make sure that the dependent objects are reatched as well.

Q: How would you reatach detached objects to a session when the same object has already been loaded into the session?
A: You can use the session.merge() method call.

Q: What are the general considerations or best practices for defining your Hibernate persistent classes?
A: 1.You must have a default no-argument constructor for your persistent classes and there should be getXXX() (i.e accessor/getter) and setXXX( i.e. mutator/setter) methods for all your persistable instance variables.
2.You should implement the equals() and hashCode() methods based on your business key and it is important not to use the id field in your equals() and hashCode() definition if the id field is a surrogate key (i.e. Hibernate managed identifier). This is because the Hibernate only generates and sets the field when saving the object.
3. It is recommended to implement the Serializable interface. This is potentially useful if you want to migrate around a multi-processor cluster.
4.The persistent class should not be final because if it is final then lazy loading cannot be used by creating proxy objects.
5.Use XDoclet tags for generating your *.hbm.xml files or Annotations (JDK 1.5 onwards), which are less verbose than *.hbm.xml files.

Q: What does ORM consists of?
A: 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

Q: What are the ORM level?
A: The ORM levels are:
* Pure relational (stored procedure.)
* Light objects mapping (JDBC)
* Medium object mapping
* Full object Mapping (composition,inheritance, polymorphism, persistence by reachability)

Q: What is CRUD?
A: A CRUD operation deals with creating , retriving , updating and deleting from the table.
We have already described previously how to persist "Employee" Class to database. Here we are adding more operation on that
Employee Class.

    Creating/Persisting the class to databae
    Retriving records from database
    Updating decord(Condition : Where sal is 8000 ,update sal to 11000)
    Deleting decord (condition: where deptno is 30)

Q: Difference between get and load in Hibernate?
A: get vs load is one of the most frequently asked Hibernate Interview question, since correct understanding of both get() and load() is require to effectively using Hibernate. Main difference between get and load is that, get will hit the database if object is not found in the cache and returned completely initialized object, which may involve several database call while load() method can return proxy, if object is not found in cache and only hit database if any method other than getId() is called. This can save lot of performance in some cases. You can also see difference between get and load in Hibernate for more differences and detailed discussion on this question.

Q: Difference between save, persist and saveOrUpdate methods in Hibernate?
A: After get vs load, this is another Hibernate Interview question which appears quite often. All three methods i.e. save(), saveOrUpdate() and persist() is used to save objects into database, but has subtle differences e.g. save() can only INSERT records but saveOrUpdate() can either INSERT or UPDATE records. Also, return type of save() is a Serializable object, while return type of persist() method is void. You can also check save vs persist vs saveOrUpdate for complete differences between them in hibernate.

Q: What is named SQL query in Hibernate?
A: This Hibernate Interview question is related to query functionality provided by Hibernate. Named queries are SQL queries which are defined in mapping document using <sql-query> tag and called using Session.getNamedQuery() method. Named query allows you to refer a particular query by the name you provided, by the way you can define named query in hibernate either by using annotations or xml mapping file, as I said above. @NameQuery is used to define single named query and @NameQueries is used to define multiple named query in hibernate.

Q: What is SessionFactory in Hibernate? is SessionFactory thread-safe?
A: Another common Interview questions related to Hibernate framework. SessionFactory as name suggest is a factory to create hibernate Session objects. SessionFactory is often built during start-up and used by application code to get session object. It acts as single data store and its also thread-safe so that multiple thread can use same SessionFactory. Usually a Java JEE application has just one SessionFactory, and individual threads, which are servicing client’s request obtain hibernate Session instances from this factory, that’s why any implementation of SessionFactory interface must be thread-safe. Also internal state of SessionFactory, which contains all meta data about Object/Relational mapping is Immutable and can not be changed once created.

Q: What is Session in Hibernate? Can we share single Session among multiple threads in Hibernate?
A: This is usually asked as follow-up question of previous Hibernate Interview question. After SessionFactory its time for Session. Session represent a small unit of work in Hibernate, they maintain connection with database and they are not thread-safe, it means you can not share Hibernate Session between multiple threads. Though Session obtains database connection lazily it's good to close session as soon as you are done with it.

Q: What is difference between sorted and ordered collection in hibernate?
A: This is one of the easy Hibernate interview question you ever face. A sorted collection is sorted in memory by using Java Comparator, while a ordered collection uses database's order by clause for ordering. For large data set it's better to use ordered collection to avoid any OutOfMemoryError in Java, by trying to sort them in memory.

Q: What is difference between transient, persistent and detached object in Hibernate?
A: In Hibernate, Object can remain in three state transient, persistent or detached.  An object which is associated with Hibernate session is called persistent object. Any change in this object will reflect in database based upon your flush strategy i.e. automatic flush whenever any property of object change or explicit flushing by calling Session.flush() method. On the other hand if an object which is earlier associated with Session, but currently not associated with it are called detached object. You can reattach detached object to any other session by calling either update() or saveOrUpdate() method on that session. Transient objects are newly created instance of persistence class, which is never associated with any Hibernate Session. Similarly you can call persist() or save() methods to make transient object persistent. Just remember, here transient doesn’t represent transient keyword in Java, which is altogether different thing.

Q: What does Session lock() method do in Hibernate?
A: This one is one of the tricky Hibernate Interview question, because Session's lock() method reattach object without synchronizing or updating with database. So you need to be very careful while using lock() method. By the way you can always use Session's update() method to sync with database during reattachment. Some time this Hibernate question is also asked as what is difference between Session's lock() and update() method. You can use this key point to answer that question as well.

Q: What is Second level Cache in Hibernate?
A: This is one of the first interview question related to caching in Hibernate, you can expect few more. Second level Cache is maintained at SessionFactory level and can improve performance by saving few database round trip. Another worth noting point is that second level cache is available to whole application rather than any particular session.

Q: What is query cache in Hibernate ?
A: This question, Some times asked as a follow-up of last Hibernate Interview question, QueryCache actually stores result of sql query for future calls. Query cache can be used along with second level cache for improved performance. Hibernate support various open source caching solution to implement Query cache e.g. EhCache.

Q: Why it's important to provide no argument constructor in Hibernate Entities?
A: Every Hibernate Entity class must contain a no argument constructor, because Hibernate framework creates instance of them using Reflection API, by calling Class.newInstance() method. This method will throw InstantiationException if it doesn't found no argument constructor inside Entity class.

Q: Can we make an Hibernate Entity Class final?
A: Yes, you can make an Hibernate Entity class final, but that's not a good practice. Since Hibernate uses proxy pattern for performance improvement in case of lazy association, by making an entity final, Hibernate will no longer be able to use proxy, because Java doesn't allow extension of final class, thus limiting your performance improvement options. Though, you can avoid this penalty, if your persistent class is an implementation of interface, which declares all public methods defined in Entity class.

Q: What is Hibernate?
A: Hibernate is an ORM (Object Relational Mapping) and persistent framework. The framework helps to map plain java object to relational database table using xml configuration file.
The framework helps to perform following things.
• Perform basic CURD operations.
• Write queries referring to java classes (HQL queries).
• Facilities to specify metadata.
• Dirty checking, lazy association fetching.

Q: Why hibernate and how does it help in the programming?
A: The main advantage of Hibernate (ORM) framework is that it shields developer to write a messy SQL. Apart from that ORM provides following benefits.
• Improve Productivity of the developer by providing high level object oriented API (e.g. API for easily maintaining the connection to data base, mapping java classes to relational database tables), less java code to write, helps to avoid writing SQL query.
• Improved performance by providing sophisticated caching, lazy loading and eager loading features.
• Provide portability, the framework helps to generate database specific SQL for you.

Q: How will you configure Hibernate?
A: To configure hibernate, you need hibernate.cfg.xml or hibernate.properties file and *.hbm.xml files, all these files are used by Configuration class to create sessionFactory, which in turn creates the session instances. Session instances are the primary interface for persistence services.
The hibernate.cfg.xml or hibernate.properties files are used to configure the hibernate service (database connection driver class, database connection URL, connection user name, connection password, dialect, mapping resources etc.).
The *hbm.xml files are used for mapping persistent objects to relational database.
From Java 5 onwards you can configure and map persistent objects through annotations.

Q: Which settings will be loaded if both hibernate.properties and hibernat.cf.xml files are present in the classpath?
A: If both hibernate.properties and hibernate.cfg.xml files are present in the classpath then hibernate.cfg.xml file will override the settings found in hibernate.properties. So please make sure that your project should include either hibernate.properties or hibernate.cfg.xml file.

Q: What are the Core interfaces of Hibernate framework?
A: There are five core interfaces being used extensively in every Hibernate application. Using these interfaces you can store or retrieve any persistent objects and also control transactions.
- Session interface
- SessionFactory interface
- Configuration interface
- Transaction interface
- Query and Criteria interfaces

Q: What is the role of Session interface in Hibernate?
A: The session interface is the primary interface used in Hibernate Application. It is single threaded sort-lived object and represents conversation between Application and the persistent store. It helps to create query objects to retrieve persistent objects.
You can get the session object from session factory
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

Q: What is the role of SessionFactory?
A: The application obtains session object from SessionFactory interface. Typically there should be only one sessionFacory for whole application and is loaded during application initialization. The SessionFactory caches generate SQL Statement and other mapping metadata that Hibernate use at runtime. It also hold cached data that has been read in one unit of work and can be reused in a future unit of work.
You can get the instance of SessionFactory by the configuration object as below
SessionFactory sessionFactory = configuration.buildSessionFactory();

Q: How do you implement one to one relationship in Hibernate with XML mapping?
A: For example you have table emp and emp_detail and assuming there is a one to one relationship between them. For the above tables you have to create corresponding POJO classes and hbm.xml files.
So for emp table the java class is Employee.java with property empId and xml file is emp.hbm.xml.
And for emp_details the java class is EmployeeDetail.java (properties are name, address etc.) and xml file is empdetail.hbm.xml.
So the final code will look like as below

package com.test.onetoone.mapping

public class Employee implements java.io.Serializable{
                private Integer empId;
                private EmployeeDetail empDetail;
}
package com.test.onetoone.mapping
public class EmployeeDetail implements java.io.Serializable{
                private Integer empId;
                private Employee emp;
                private String name;
                private String address;
}
----- emp.hbm.xml ----
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
                <class name="com.test.onetoone.mapping.Employee" table="emp">
                                <id name="empId" type="java.lang.Integer">
                                                <column name="EMP_ID" />
                                                <generator class="identity" />
                                </id>
                                <one-to-one name="empDetail" class="com.test.onetoone.mapping.EmployeeDetail" cascade="save-update"></one-to-one>
                </class>
</hibernate-mapping>

***********************empdetails.hbm.xml*******************
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
                <class name="com.test.onetoone.mapping.EmployeeDetail" table="emp_detail" catalog="mkyongdb">
                                <id name="stockId" type="java.lang.Integer">
                                                <column name="EMP_ID" />
                                                <generator class="foreign">
                                                                <param name="property">emp</param>
                                                </generator>
                                </id>
                                <one-to-one name="emp" class="com.test.onetoone.mapping.Employee" constrained="true"></one-to-one>
                                <property name="name" type="string">
                                                <column name="EMP_NAME" length="100" not-null="true" />
                                </property>
                                <property name="address" type="string">
                                                <column name="EMP_ADDR" not-null="true" />
                                </property>
                </class>
</hibernate-mapping>

Q: How do you implement one to one relationship in Hibernate with java annotation?
A: Taking the same Employee and Employee Details example of the above question.

Employee.java
package com.test.onetoone.mapping
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import static javax.persistence.GenerationType.IDENTITY;
import javax.persistence.Id;
import javax.persistence.OneToOne;
import javax.persistence.Table;
@Entity
@Table(name = "emp")
public class Employee implements java.io.Serializable{
                private Integer empId;
                private EmployeeDetail empDetail;
                public Employee(){}
               
                @Id
                @GeneratedValue(strategy = IDENTITY)
                @Column(name = "EMP_ID", unique = true, nullable = false)
                public Integer getEmpId(){
                                return this.empId;
                }
                public void setEmpId(Integer empId){
                                this.empId = empId;
                }
                @OneToOne(fetch = FetchType.LAZY, mappedBy = "emp", cascade = CascadeType.ALL)
                public EmployeeDetail getEmpDetail() {
                                return this.empDetail;
                }
                public void setEmpDetail(EmployeeDetail empDetail) {
                                this.empDetail = empDetail;
                }
}

File: EmployeeDetail.java
package com.test.onetoone.mapping
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.OneToOne;
import javax.persistence.PrimaryKeyJoinColumn;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import org.hibernate.annotations.GenericGenerator;
import org.hibernate.annotations.Parameter;

@Entity
@Table(name = "emp_detail")
public class EmployeeDetail implements java.io.Serializable {
                private Integer empId;
                private Employee emp;
                private String name;
                private String address;
                public EmployeeDetail() {
                }

                public EmployeeDetail(Employee emp, String name, String address) {
                                this.emp = emp;
                                this.name = name;
                                this.address = address;
                }

                @GenericGenerator(name = "generator", strategy = "foreign",
                parameters = @Parameter(name = "property", value = "emp"))
                @Id
                @GeneratedValue(generator = "generator")
                @Column(name = "EMP_ID", unique = true, nullable = false)
                public Integer getEmpId() {
                                return this.empId;
                }
                public void setEmpId(Integer empId) {
                                this.empId = empId;
                }

                @OneToOne(fetch = FetchType.LAZY)
                @PrimaryKeyJoinColumn
                public Employee getEmp() {
                                return this.emp;
                }

                public void setEmp(Employee emp) {
                                this.emp = emp;
                }
                @Column(name = "ADDRESS", nullable = false, length = 400)
                public String getAddress() {
                                return this.address;
                }
                public void setAddress(String address) {
                                this.address = address;
                }
                @Column(name = "EMP_NAME", nullable = false)
                public String getName() {
                                return this.name;
                }
                public void setName(String name) {
                                this.name = name;
                }
}

3. Hibernate Configuration File
Puts annotated classes Employee.java and EmployeeDetail.java in your Hibernate configuration file, and also MySQL connection details.
File : hibernate.cfg.xml
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
                <session-factory>
                                <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
                                <property name="hibernate.connection.url">jdbc:mysql://localhost:3306/mytestdb</property>
                                <property name="hibernate.connection.username">root</property>
                                <property name="hibernate.connection.password">password</property>
                                <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
                                <property name="show_sql">true</property>
                                <mapping class="com.test.onetoone.mapping.Employee" />
                                <mapping class="com.test.onetoone.mapping.EmployeeDetail" />
                </session-factory>
</hibernate-configuration>

Q: How do you implement one to many relationships in Hibernate?
A: For one to many relationships we can consider the example Author and Books (i.e. one Author can have written many books).
Below code will help you to understand how you can implement one to many relationship in hibernate.

File: Author.java
package com.test.one.to.many;
java.util.Set;
public class Author implements java.io.Serializable{
                private Integer authorId;
                private String authorName;
                private Set<Book> books;
                // getter and setter
}

File: Book.java
package com.test.one.to.many;
public class Book implements java.io.Serializable{
                private Author author;
                private Integer bookId;
                private String bookName;
                // getter and setter
}

File: Author.hbm.xml
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
                <class name="com.test.one.to.many.Author" table="author">
                                <id name="authorId" type="java.lang.Integer">
                                                <column name="AUTHOR_ID" />
                                                <generator class="identity" />
                                </id>
                                <property name="authorName" type="string">
                                                <column name="AUTHOR_NAME" length="100" not-null="true" unique="true" />
                                </property>

                                <set name="books" table="book" inverse="true" lazy="true" fetch="select">
                                                <key>
                                                                <column name="AUTHOR_ID" not-null="true" />
                                                </key>
                                                <one-to-many class="com.test.one.to.many.Book" />
                                </set>
                </class>
</hibernate-mapping>

File: Book.hbm.xml
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
                <class name="com.test.one.to.many.Book" table="book">
                                <id name="bookId" type="java.lang.Integer">
                                                <column name="BOOK_ID" />
                                                <generator class="identity" />
                                </id>
                                <many-to-one name="author" class="com.test.one.to.many.Author" fetch="select">
                                                <column name="AUTHOR_ID" not-null="true" />
                                </many-to-one>
                                <property name="bookName" type="string">
                                                <column name="BOOK_NAME" />
                                </property>
                </class>
</hibernate-mapping>

File: hibernate.cfg.xml

<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
                <session-factory>
                                <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
                                <property name="hibernate.connection.url">jdbc:mysql://localhost:3306/mytestdb</property>
                                <property name="hibernate.connection.username">root</property>
                                <property name="hibernate.connection.password">password</property>
                                <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
                                <property name="show_sql">true</property>
                                <property name="format_sql">true</property>
                                <mapping resource="com/test/one/to/many/Author.hbm.xml" />
                                <mapping resource="com/test/one/to/many/Book.hbm.xml" />
                </session-factory>
</hibernate-configuration>

Q: How to implement one to many relationships with Annotation?
A: You can implement one to many relationship with the help Annotation also. Below code will help you to understand the one to many relationship with java Annotation.

File : Author.java
package com.test.one.to.many;
import java.util.Set;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import static javax.persistence.GenerationType.IDENTITY;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import javax.persistence.Table;

@Entity
@Table(name = "Author")
public class Author implements java.io.Serializable {
                private Integer authorId;
                private String authorName;
                private Set<Book> books;
                // getter and setter

                public Author() {
                }
                @Id
                @GeneratedValue(strategy = IDENTITY)
                @Column(name = "AUTHOR_ID", unique = true, nullable = false)
                public Integer getAuthorId() {
                                return this.authorId;
                }

                public void setAuthorId(Integer authorId) {
                                this.authorId = authorId;
                }

                @Column(name = "AUTHOR_NAME", nullable = false, length = 100)
                public String getAuthorName() {
                                return this.authorName;
                }

                public void setAuthorName(String authorName) {
                                this.authorName = authorName;
                }

                @OneToMany(fetch = FetchType.LAZY, mappedBy = "author")
                public Set<Book> getBooks() {
                                return this.books;
                }
                public void setBooks(Set<Book> books) {
                                this.books = books;
                }
}

File : Book.java
package com.test.one.to.many;
import java.util.Date;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import static javax.persistence.GenerationType.IDENTITY;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
import javax.persistence.UniqueConstraint;

@Entity
@Table(name = "book")
public class Book implements java.io.Serializable {
                private Author author;
                private Integer bookId;
                private String bookName;
                public Book() {}

                @Id
                @GeneratedValue(strategy = IDENTITY)
                @Column(name = "BOOK_ID", unique = true, nullable = false)
                public Integer getBookId() {
                                return this.bookId;
                }
                public void setBookId(Integer bookId) {
                                this.bookId = bookId;
                }
                @ManyToOne(fetch = FetchType.LAZY)
                @JoinColumn(name = "AUTHOR_ID", nullable = false)
                public Author getAuthor() {
                                return this.auther;
                }
                public void setAuther(Author author) {
                                this.auther = auther;
                }
                @Column(name = "BOOK_NAME", length = 400, nulaable=false)
                public Float getBookName() {
                                return this.bookName;
                }
                public void setBookName(String bookName) {
                                this.bookName = bookName;
                }
}

3. Hibernate Configuration File
Puts annotated classes Author.java and Book.java in hibernate.cfg.xml like this :
File : hibernate.cfg.xml

<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
                <session-factory>
                                <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
                                <property name="hibernate.connection.url">jdbc:mysql://localhost:3306/mytestdb</property>
                                <property name="hibernate.connection.username">root</property>
                                <property name="hibernate.connection.password">password</property>
                                <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
                                <property name="show_sql">true</property>
                                <mapping class="com.test.one.to.many.Author" />
                                <mapping class="com.test.one.to.many.Book" />
                </session-factory>
</hibernate-configuration>

Q: How will you integrate Hibernate with spring framework?
A: To integrate hibernate with spring framework, the hibernate configuration will go in spring configuration file.
The configuration file will look like as below

<beans>
                <bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer" p:location="/WEB-INF/jdbc.properties"></bean>
                <!—jdbc.properties database related properties -->
                <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close"
                                p:driverClassName="${jdbc.driverClassName}"
                                p:url="${jdbc.databaseurl}" p:username="${jdbc.username}"
                                p:password="${jdbc.password}"></bean>

                <bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
                                <property name="dataSource" ref="dataSource"></property>
                                <property name="configLocation">
                                                <value>classpath:hibernate.cfg.xml</value>
                                </property>
                                <property name="configurationClass">
                                                <value>org.hibernate.cfg.AnnotationConfiguration</value>
                                </property>
                                <property name="hibernateProperties">
                                                <props>
                                                                <prop key="hibernate.dialect">${jdbc.dialect}</prop>
                                                                <prop key="hibernate.show_sql">true</prop>
                                                </props>
                                </property>
                </bean>
               
                <bean id="employeeDAO" class="com.test.dao.EmployeeDaoImpl"></bean>
                <bean id="employeeManager" class="com.test.service.EmployeeManagerImpl"></bean>

                <tx:annotation-driven />

                <bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager">
                                <property name="sessionFactory" ref="sessionFactory"></property>
                </bean>
</beans>

Q: What are the Collection types in Hibernate?
A: • Bag
• Set
• List
• Array
• Map

Q: What is HibernateTemplate?
A: The spring framework provides HibernateTemplate (org.springframework.orm.hibernate.HibernateTemplate) which is kind of helper class and provides following benefits.
- HibernateTemplate class simplifies interaction with Hibernate session.
- Common functions are simplified to single method calls.
- Sessions are automatically closed.
- Exception are automatically caught and converted to runtime exceptions.

Q: What is the difference between load() and get() method?
A: 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 obout the object existance in the database.
- If object does not exists in the database, the get() method will return null.
- get() method will hit database immediately.

Q: What is lazy fetching in Hibernate?
A: In Hibernate Lazy fetching is associated with child objects loading for its parents. Through Hibernate mapping file (.hbm.xml) you can specified the selection of loading child objects. By default Hibernate does not load child objects. Lazy=rue means not to load the child objects.

Q: What is the difference between merge and update method?
A: 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.

Q: How do you define sequence generated primary key in hibernate?
A: Using <generator> tag.
Example:-
<id column="CUST_ID" name="id" type="java.lang.Long">
                <generator class="sequence">
                                <param name="table">SEQUENCE_NAME</param>
                <generator>
</id>

Q: What are the different types of caches in Hibernate?
A: 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.

Q: What do you mean by Named – SQL query?
A: 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("Deepak", name).setMaxResults(50).list();

Q: What’s Hibernate?
A: Hibernate is a popular framework of Java which allows an efficient Object Relational mapping using configuration files in XML format. After java objects mapping to database tables, database is used and handled using Java objects without writing complex database queries.

Q: What is ORM?
A: ORM (Object Relational Mapping) is the fundamental concept of Hibernate framework which maps database tables with Java Objects and then provides various API’s to perform different types of operations on the data tables.

Q: How properties of a class are mapped to the columns of a database table in Hibernate?
A: Mappings between class properties and table columns are specified in XML file as in the below example:

Q: What’s the usage of Configuration Interface in hibernate?
A: Configuration interface of hibernate framework is used to configure hibernate. It’s also used to bootstrap hibernate. Mapping documents of hibernate are located using this interface.

Q: How can we use new custom interfaces to enhance functionality of built-in interfaces of hibernate?
A: We can use extension interfaces in order to add any required functionality which isn’t supported by built-in interfaces.

Q: Should all the mapping files of hibernate have .hbm.xml extension to work properly?
A: No, having .hbm.xml extension is a convention and not a requirement for hibernate mapping file names. We can have any extension for these mapping files.

Q: How do we create session factory in hibernate?
A: hibernate interview questions
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(&amp;amp;quot;myinstance/configuration.hbm.xml&amp;amp;quot;); config.setProperties( System.getProperties() ); SessionFactory sessions = config.buildSessionFactory();
Configuration config = new Configuration();
config.addResource(&amp;amp;quot;myinstance/configuration.hbm.xml&amp;amp;quot;);
config.setProperties( System.getProperties() );
SessionFactory sessions = config.buildSessionFactory();

Q: What are POJOs and what’s their significance?
A: 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.

Q: What’s HQL?
A: HQL is the query language used in Hibernate which is an extension of SQL. HQL is very efficient, simple and flexible query language to do various type of operations on relational database without writing complex database queries.

Q: How can we invoke stored procedures in hibernate?
A: In hibernate we can execute stored procedures using code as below:

[xml]
<sql-query name="getStudents" callable="true">
                <return alias="st" class="Student">
                <return-property name="std_id" column="STD_ID"/>
                <return-property name="s_name" column="STD_NAME"/>
                <return-property name="s_dept" column="STD_DEPARTMENT"/>
                                { ? = call selectStudents() }
                </return>
</sql-query>
[/xml]

Q: What is criteria API?
A: Criteria is a simple yet powerful API of hibernate which is used to retrieve entities through criteria object composition.

Q: What are the benefits of using Hibernate template?
A: Following are some key benefits of using Hibernate template:
a. Session closing is automated.
b. Interaction with hibernate session is simplified.
c. Exception handling is automated.

Q: How can we see hibernate generated SQL on console?
A: We need to add following in hibernate configuration file to enable viewing SQL on the console for debugging purposes:

[xml]
<property name="show_sql">true</property>
[/xml]

Q: What are the two types of collections in hibernate?
A: Following are the two types of collections in hibernate:
a. Sorted Collection
b. Order Collection

Q: What’s the difference between session.save() and session.saveOrUpdate() methods in hibernate?
A: Sessionsave() 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.
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.

Q: What the benefits are of hibernate over JDBC?
A: a. Hibernate can be used seamlessly with any type of database as its database independent while in case of JDBC, developer has to write database specific queries.
b. Using hibernate, developer doesn’t need to be an expert of writing complex queries as HQL simplifies query writing process while in case of JDBC, its job of developer to write and tune queries.
c. In case of hibernate, there is no need to create connection pools as hibernate does all connection handling automatically while in case of JDBC, connection pools need to be created.

Q: How can we get hibernate statistics?
A: We can get hibernate statistics using getStatistics() method of SessionFactory class as shown below:
SessionFactory.getStatistics()

Q: What is transient instance state in Hibernate?
A: If an instance is not associated with any persistent context and also, it has never been associated with any persistent context, then it’s said to be in transient state.

Q: How can we reduce database write action times in Hibernate?
A: Hibernate provides dirty checking feature which can be used to reduce database write times. Dirty checking feature of hibernate updates only those fields which require a change while keeps others unchanged.

Q: What’s the usage of callback interfaces in hibernate?
A: Callback interfaces of hibernate are useful in receiving event notifications from objects. For example, when an object is loaded or deleted, an event is generated and notification is sent using callback interfaces.

Q: When an instance goes in detached state in hibernate?
A: When an instance was earlier associated with some persistent context (e.g. a table) and is no longer associated, it’s called to be in detached state.

Q: What the four ORM levels are in hibernate?
A: Following are the four ORM levels in hibernate:
a. Pure Relational
b. Light Object Mapping
c. Medium Object Mapping
d. Full Object Mapping

Q: What’s transaction management in hibernate? How it works?
A: Transaction management is the process of managing a set of statements or commands. In hibernate; transaction management is done by transaction interface as shown in below code:

[java]
Session s = null;
Transaction tr = null;
try {
                s = sessionFactory.openSession();
                tr = s.beginTransaction();
                doTheAction(s);
                tr.commit();
} catch (RuntimeException exc) {
                tr.rollback();
} finally {
                s.close();
}
[/java]

Q: What the two methods are of hibernate configuration?
A: We can use any of the following two methods of hibernate configuration:
a. XML based configuration ( using hibernate.cfg.xml file)
b. Programmatic configuration ( Using code logic)

Q: What is the default cache service of hibernate?
A: Hibernate supports multiple cache services like EHCache, OSCache, SWARMCache and TreeCache and default cache service of hibernate is EHCache.

Q: What are the two mapping associations used in hibernate?
A: In hibernate; we have following two types of mapping associations between entities:
a. One-to-One Association
b. Many-to-Many Association

Q: What’s the usage of Hibernate QBC API?
A: Hibernate Query By Criteria (QBC) API is used to create queries by manipulation of criteria objects at runtime.

Q: In how many ways, objects can be fetched from database in hibernate?
A: Hibernate provides following four ways to fetch objects from database:
a. Using HQL
b. Using identifier
c. Using Criteria API
d. Using Standard SQL

Q: How primary key is created by using hibernate?
A: Database primary key is specified in the configuration file hbm.xml. Generator can also be used to specify how primary key is being created in the database.
In the below example, deptId acts as primary key:
[xml]
<id name="deptId" type="string" >
                <column name="columnId" length="30?/>
                <generator/>
</id>
[/xml]

Q: How can we reattach any detached objects in Hibernate?
A: Objects which have been detached and are no longer associated with any persistent entities can be reattached by calling session.merge() method of session class.

Q: What are different ways to disable hibernate second level cache?
A: Hibernate second level cache can be disabled using any of the following ways:
a. By setting use_second_level_cache as false.
b. By using CACHEMODE.IGNORE
c. Using cache provider as org.hibernate.cache.NoCacheProvider

Q: What is ORM metadata?
A: All the mapping between classes and tables, properties and columns, Java types and SQL types etc is defined in ORM metadata.

Q: Which one is the default transaction factory in hibernate?
A: With hibernate 3.Q: default transaction factory is JDBCTransactionFactory.

Q: What’s the role of JMX in hibernate?
A: 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.

Q: How can we bind hibernate session factory to JNDI ?
A: Hibernate session factory can be bound to JNDI by making configuration changes in hibernate.cfg file.

Q: In how many ways objects can be identified in Hibernate?
A: Object identification can be done in hibernate in following three ways:
a. Using Object Identity: Using == operator.
b. Using Object Equality: Using equals() method.
c. Using database identity: Relational database objects can be identified if they represent same row.

Q: What different fetching strategies are of hibernate?
A: Following fetching strategies are available in hibernate:
1.      Join Fetching
2.     Batch Fetching
3.      Select Fetching
4.     Sub-select Fetching

Q: How mapping of java objects is done with database tables?
A: To map java objects with database tables, we need to have Java beans properties names same as column names of a database table. Then mapping is provided in hbm.xml file as given below:

[xml]
<hibernate-mapping>
                <class name="Student"  table="tbl_student">
                                <property  column="studentname" length="2Q: name="studentName" not-null="true"  type="java.lang.String"/>
                                <property  column="studentDisciplne" length="2Q: name="studentDiscipline" not-null="true"  type="java.lang.String"/>
                </class>
</hibernate-mapping>
[/xml]

Q: What are derived properties in hibernate?
A: Derived properties are those properties which are not mapped to any columns of a database table. Such properties are calculated at runtime by evaluation of any expressions.

Q: What is meant by a Named SQL Query in hibernate and how it’s used?
A: Named SQL queries are those queries which are defined in mapping file and are called as required anywhere.
For example, we can write a SQL query in our XML mapping file as follows:

[xml]
<sql-query name = “studentdetails">
                <return alias="std"/>
                SELECT std.STUDENT_ID AS {std.STUDENT_ID}, std.STUDENT_DISCIPLINE AS {std.discipline}, FROM Student std WHERE std.NAME LIKE :name
</sql-query>
[/xml]

Then this query can be called as follows:

[java]
List students = session.getNamedQuery(&amp;quot;studentdetails&amp;quot;).setString(&amp;quot;TomBrady&amp;quot;, name).setMaxResults(50).list();
[/java]

Q: What’s the difference between load() and get() method in hibernate?
A: Load() methods results in an exception if the required records isn’t found in the database while get() method returns null when records against the id isn’t found in the database.
So, ideally we should use Load() method only when we are sure about existence of records against an id.

Q: What’s the use of version property in hibernate?
A: Version property is used in hibernate to know whether an object is in transient state or in detached state.

Q: What is attribute oriented programming?
A: In Attribute oriented programming, a developer can add Meta data (attributes) in the java source code to add more significance in the code. For Java (hibernate), attribute oriented programming is enabled by an engine called XDoclet.

Q: What’s the use of session.lock() in hibernate?
A: session.lock() method of session class is used to reattach an object which has been detached earlier. This method of reattaching doesn’t check for any data synchronization in database while reattaching the object and hence may lead to lack of synchronization in data.

Q: Does hibernate support polymorphism?
A: Yes, hibernate fully supports polymorphism. Polymorphism queries and polymorphism associations are supported in all mapping strategies of hibernate.

Q: What the three inheritance models are of hibernate?
A: Hibernate has following three inheritance models:
a. Tables Per Concrete Class
b. Table per class hierarchy
c. Table per sub-class

Q: How can we map the classes as immutable?
A: If we don’t want an application to update or delete objects of a class in hibernate, we can make the class as immutable by setting mutable=false

Q: What’s general hibernate flow using RDBMS?
A: General hibernate flow involving RDBMS is as follows:
a. Load configuration file and create object of configuration class.
b. Using configuration object, create sessionFactory object.
c. From sessionFactory, get one session.
d. Create HQL query.
e. Execute HQL query and get the results. Results will be in the form of a list.

Q: What is Light Object Mapping?
A: Light Object Mapping is one of the levels of ORM quality in which all entities are represented as classes and they are mapped manually.

Q: What’s difference between managed associations and hibernate associations?
A: Managed associations relate to container management persistence and are bi-directional while hibernate associations are unidirectional.

Q: What is Hibernate Framework?
A: 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.
Similarly hibernate configurations are flexible and can be done from XML configuration file as well as programmatically. For a quick overview of hibernate framework usage, you can go through Hibernate Beginners Tutorial.

Q: What is Java Persistence API (JPA)?
A: Java Persistence API (JPA) provides specification for managing the relational data in applications. Current JPA version 2.1 was started in July 2Q: as JSR 3Q: JPA 2.1 was approved as final on Q: May 2013.
JPA specifications is defined with annotations in javax.persistence package. Using JPA annotation helps us in writing implementation independent code.

Q: What are the important benefits of using Hibernate Framework?
A: Some of the important benefits of using hibernate framework are:
    Hibernate eliminates all the boiler-plate code that comes with JDBC and takes care of managing resources, so we can focus on business logic.
    Hibernate framework provides support for XML as well as JPA annotations, that makes our code implementation independent.
    Hibernate provides a powerful query language (HQL) that is similar to SQL. However, HQL is fully object-oriented and understands concepts like inheritance, polymorphism and association.
    Hibernate is an open source project from Red Hat Community and used worldwide. This makes it a better choice than others because learning curve is small and there are tons of online documentations and help is easily available in forums.
    Hibernate is easy to integrate with other Java EE frameworks, it’s so popular that Spring Framework provides built-in support for integrating hibernate with Spring applications.
    Hibernate supports lazy initialization using proxy objects and perform actual database queries only when it’s required.
    Hibernate cache helps us in getting better performance.
    For database vendor specific feature, hibernate is suitable because we can also execute native sql queries.
Overall hibernate is the best choice in current market for ORM tool, it contains all the features that you will ever need in an ORM tool.

Q: What are the advantages of Hibernate over JDBC?
A: 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.

Q: Name some important interfaces of Hibernate framework?
A: 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.

Q: What is hibernate configuration file?
A: 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.

Q: What is hibernate mapping file?
A: 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.

Q: Name some important annotations used for Hibernate mapping?
A: Hibernate supports JPA annotations and it has some other annotations in org.hibernate.annotations package. Some of the important JPA and hibernate annotations used are:

    javax.persistence.Entity: Used with model classes to specify that they are entity beans.
    javax.persistence.Table: Used with entity beans to define the corresponding table name in database.
    javax.persistence.Access: Used to define the access type, either field or property. Default value is field and if you want hibernate to use getter/setter methods then you need to set it to property.
    javax.persistence.Id: Used to define the primary key in the entity bean.
    javax.persistence.EmbeddedId: Used to define composite primary key in the entity bean.
    javax.persistence.Column: Used to define the column name in database table.
    javax.persistence.GeneratedValue: Used to define the strategy to be used for generation of primary key. Used in conjunction with javax.persistence.GenerationType enum.
    javax.persistence.OneToOne: Used to define the one-to-one mapping between two entity beWe have other similar annotations as OneToMany, ManyToOne and ManyToMany
    org.hibernate.annotations.Cascade: Used to define the cascading between two entity beused with mappings. It works in conjunction with org.hibernate.annotations.CascadeType
    javax.persistence.PrimaryKeyJoinColumn: Used to define the property for foreign key. Used with org.hibernate.annotations.GenericGenerator and org.hibernate.annotations.Parameter

Here are two classes showing usage of these annotations.

Employee.java
package com.journaldev.hibernate.model;

import javax.persistence.Access;
import javax.persistence.AccessType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.OneToOne;
import javax.persistence.Table;

import org.hibernate.annotations.Cascade;

@Entity
@Table(name = "EMPLOYEE")
@Access(value=AccessType.FIELD)
public class Employee {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "emp_id")
    private long id;

    @Column(name = "emp_name")
    private String name;

    @OneToOne(mappedBy = "employee")
    @Cascade(value = org.hibernate.annotations.CascadeType.ALL)
    private Address address;

    //getter setter methods
}

Address.java
package com.journaldev.hibernate.model;

import javax.persistence.Access;
import javax.persistence.AccessType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.OneToOne;
import javax.persistence.PrimaryKeyJoinColumn;
import javax.persistence.Table;

import org.hibernate.annotations.GenericGenerator;
import org.hibernate.annotations.Parameter;

@Entity
@Table(name = "ADDRESS")
@Access(value=AccessType.FIELD)
public class Address {

    @Id
    @Column(name = "emp_id", unique = true, nullable = false)
    @GeneratedValue(generator = "gen")
    @GenericGenerator(name = "gen", strategy = "foreign", parameters = { @Parameter(name = "property", value = "employee") })
    private long id;

    @Column(name = "address_line1")
    private String addressLine1;

    @OneToOne
    @PrimaryKeyJoinColumn
    private Employee employee;

    //getter setter methods
}

Q: What is Hibernate SessionFactory and how to configure it?
A: SessionFactory is the factory class used to get the Session objects. SessionFactory is responsible to read the hibernate configuration parameters and connect to the database and provide Session objects. Usually an application has a single SessionFactory instance and threads servicing client requests obtain Session instances from this factory.
The internal state of a SessionFactory is immutable. Once it is created this internal state is set. This internal state includes all of the metadata about Object/Relational Mapping.
SessionFactory also provide methods to get the Class metadata and Statistics instance to get the stats of query executions, second level cache details etc.

Q: Hibernate SessionFactory is thread safe?
A: Internal state of SessionFactory is immutable, so it’s thread safe. Multiple threads can access it simultaneously to get Session instances.

Q: What is Hibernate Session and how to get it?
A: Hibernate Session is the interface between java application layer and hibernate. This is the core interface used to perform database operations. Lifecycle of a session is bound by the beginning and end of a transaction.
Session provide methods to perform create, read, update and delete operations for a persistent object. We can execute HQL queries, SQL native queries and create criteria using Session object.

Q: Hibernate Session is thread safe?
A: Hibernate Session object is not thread safe, every thread should get it’s own session instance and close it after it’s work is finished.

Q: What is difference between openSession and getCurrentSession?
A: Hibernate SessionFactory getCurrentSession() method returns the session bound to the context. But for this to work, we need to configure it in hibernate configuration file. Since this session object belongs to the hibernate context, we don’t need to close it. Once the session factory is closed, this session object gets closed.
                <property name="hibernate.current_session_context_class">thread</property>
Hibernate SessionFactory openSession() method always opens a new session. We should close this session object once we are done with all the database operations. We should open a new session for each request in multi-threaded environment.
There is another method openStatelessSession() that returns stateless session, for more details with examples please read Hibernate openSession vs getCurrentSession.

Q: What is difference between Hibernate Session get() and load() method?
A: Hibernate session comes with different methods to load data from database. get and load are most used methods, at first look they seems similar but there are some differences between them.
    get() loads the data as soon as it’s called whereas load() returns a proxy object and loads data only when it’s actually required, so load() is better because it support lazy loading.
    Since load() throws exception when data is not found, we should use it only when we know data exists.
    We should use get() when we want to make sure data exists in the database.

For clarification regarding the differences, please read Hibernate get vs load.

Q: What is hibernate caching? Explain Hibernate first level cache?
A: As the name suggests, hibernate caches query data to make our application faster. Hibernate Cache can be very useful in gaining fast application performance if used correctly. The idea behind cache is to reduce the number of database queries, hence reducing the throughput time of the application.

Hibernate first level cache is associated with the Session object. Hibernate first level cache is enabled by default and there is no way to disable it. However hibernate provides methods through which we can delete selected objects from the cache or clear the cache completely.
Any object cached in a session will not be visible to other sessions and when the session is closed, all the cached objects will also be lost.
For better explanation, please read Hibernate First Level Cache.

Q: How to configure Hibernate Second Level Cache using EHCache?
A: EHCache is the best choice for utilizing hibernate second level cache. Following steps are required to enable EHCache in hibernate application.
    Add hibernate-ehcache dependency in your maven project, if it’s not maven then add corresponding jars.
    <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-ehcache</artifactId>
            <version>4.3.5.Final</version>
    </dependency>
               
    Add below properties in hibernate configuration file.
    <property name="hibernate.cache.region.factory_class">org.hibernate.cache.ehcache.EhCacheRegionFactory</property>             
    <!-- For singleton factory -->
    <!-- <property name="hibernate.cache.region.factory_class">org.hibernate.cache.ehcache.SingletonEhCacheRegionFactory</property>
    -->
    <!-- enable second level cache and query cache -->
    <property name="hibernate.cache.use_second_level_cache">true</property>
    <property name="hibernate.cache.use_query_cache">true</property>
    <property name="net.sf.ehcache.configurationResourceName">/myehcache.xml</property>
    Create EHCache configuration file, a sample file would look like below.
               
    myehcache.xml
    <?xml version="1.Q: encoding="UTF-8"?>
    <ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:noNamespaceSchemaLocation="ehcache.xsd" updateCheck="true"
        monitoring="autodetect" dynamicConfig="true">
     
        <diskStore path="java.io.tmpdir/ehcache" />
     
        <defaultCache maxEntriesLocalHeap="100Q: eternal="false"
            timeToIdleSeconds="1Q: timeToLiveSeconds="1Q: diskSpoolBufferSizeMB="30"
            maxEntriesLocalDisk="100000Q: diskExpiryThreadIntervalSeconds="120"
            memoryStoreEvictionPolicy="LRU" statistics="true">
            <persistence strategy="localTempSwap" />
        </defaultCache>
     
        <cache name="employee" maxEntriesLocalHeap="100Q: eternal="false"
            timeToIdleSeconds="Q: timeToLiveSeconds="10">
            <persistence strategy="localTempSwap" />
        </cache>
     
        <cache name="org.hibernate.cache.internal.StandardQueryCache"
            maxEntriesLocalHeap="Q: eternal="false" timeToLiveSeconds="120">
            <persistence strategy="localTempSwap" />
        </cache>
     
        <cache name="org.hibernate.cache.spi.UpdateTimestampsCache"
            maxEntriesLocalHeap="50Q: eternal="true">
            <persistence strategy="localTempSwap" />
        </cache>
    </ehcache>
    Annotate entity beans with @Cache annotation and caching strategy to use. For example,
    import org.hibernate.annotations.Cache;
    import org.hibernate.annotations.CacheConcurrencyStrategy;
    
    @Entity
    @Table(name = "ADDRESS")
    @Cache(usage=CacheConcurrencyStrategy.READ_ONLY, region="employee")
                public class Address {
    }

    That’s it, we are done. Hibernate will use the EHCache for second level caching, read Hibernate EHCache Example for a complete example with explanation.

Q: What are different states of an entity bean?
A: 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().

Q: What is use of Hibernate Session merge() call?
A: 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. For example program, read Hibernate merge.

Q: What is difference between Hibernate save(), saveOrUpdate() and persist() methods?
A: Hibernate save can be used to save entity to database. Problem with save() is that it can be invoked without a transaction and if we have mapping entities, then only the primary object gets saved causing data inconsistencies. Also save returns the generated id immediately.
Hibernate persist is similar to save with transaction. I feel it’s better than save because we can’t use it outside the boundary of transaction, so all the object mappings are preserved. Also persist doesn’t return the generated id immediately, so data persistence happens when needed.
Hibernate saveOrUpdate results into insert or update queries based on the provided data. If the data is present in the database, update query is executed. We can use saveOrUpdate() without transaction also, but again you will face the issues with mapped objects not getting saved if session is not flushed. For example usage of these methods, read Hibernate save vs persist.

Q: What will happen if we don’t have no-args constructor in Entity bean?
A: Hibernate uses Reflection API to create instance of Entity beusually 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 behibernate will fail to instantiate it and you will get HibernateException.

Q: What is difference between sorted collection and ordered collection, which one is better?
A: When we use Collection API sorting algorithms to sort a collection, it’s called sorted list. For small collections, it’s not much of an overhead but for larger collections it can lead to slow performance and OutOfMemory errors. Also the entity beans should implement Comparable or Comparator interface for it to work, read more at java object list sorting.

If we are using Hibernate framework to load collection data from database, we can use it’s Criteria API to use “order by” clause to get ordered list. Below code snippet shows you how to get it.
                List<Employee> empList = session.createCriteria(Employee.class).addOrder(Order.desc("id")).list();
Ordered list is better than sorted list because the actual sorting is done at database level, that is fast and doesn’t cause memory issues.

Q: What are the collection types in Hibernate?
A: There are five collection types in hibernate used for one-to-many relationship mappings.
    Bag
    Set
    List
    Array
    Map

Q: How to implement Joins in Hibernate?
A: 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.

Q: Why we should not make Entity Class final?
A: Hibernate use proxy classes for lazy loading of data, only when it’s needed. This is done by extending the entity bean, if the entity bean will be final then lazy loading will not be possible, hence low performance.

Q: What is HQL and what are it’s benefits?
A: Hibernate Framework comes with a powerful object-oriented query language – Hibernate Query Language (HQL). It’s very similar to SQL except that we use Objects instead of table names, that makes it more close to object oriented programming.
Hibernate query language is case-insensitive except for java class and variable names. So SeLeCT is the same as sELEct is the same as SELECT, but com.journaldev.model.Employee is not same as com.journaldev.model.EMPLOYEE.
The HQL queries are cached but we should avoid it as much as possible, otherwise we will have to take care of associations. However it’s a better choice than native sql query because of Object-Oriented approach. Read more at HQL Example.

Q: What is Query Cache in Hibernate?
A: 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");

Q: Can we execute native sql query in hibernate?
A: Hibernate provide option to execute native SQL queries through the use of SQLQuery object.
For normal scenarios, it is however not the recommended approach because we loose benefits related to hibernate association and hibernate first level caching. Read more at Hibernate Native SQL Query Example.

Q: What is the benefit of native sql query support in hibernate?
A: Native SQL Query comes handy when we want to execute database specific queries that are not supported by Hibernate API such as query hints or the CONNECT keyword in Oracle Database.

Q: What is Named SQL Query?
A: Hibernate provides Named Query that we can define at a central location and use them anywhere in the code. We can created named queries for both HQL and Native SQL.
Hibernate Named Queries can be defined in Hibernate mapping files or through the use of JPA annotations @NamedQuery and @NamedNativeQuery.

Q: What are the benefits of Named SQL Query?
A: Hibernate Named Query helps us in grouping queries at a central location rather than letting them scattered all over the code.
Hibernate Named Query syntax is checked when the hibernate session factory is created, thus making the application fail fast in case of any error in the named queries.
Hibernate Named Query is global, means once defined it can be used throughout the application.
However one of the major disadvantage of Named query is that it’s hard to debug, because we need to find out the location where it’s defined.

Q: What is the benefit of Hibernate Criteria API?
A: 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.
Learn some quick examples at Hibernate Criteria Example.

Q: How to log hibernate generated sql queries in log files?
A: 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.

Q: What is Hibernate Proxy and how it helps in lazy loading?
A: Hibernate uses proxy object to support lazy loading. Basically when you load data from tables, hibernate doesn’t load all the mapped objects. As soon as you reference a child or lookup object via getter methods, if the linked entity is not in the session cache, then the proxy code will go to the database and load the linked object. It uses javassist to effectively and dynamically generate sub-classed implementations of your entity objects.

Q: How to implement relationships in hibernate?
A: We can easily implement one-to-one, one-to-many and many-to-many relationships in hibernate. It can be done using JPA annotations as well as XML based configurations. For better understanding, you should go through following tutorials.
    Hibernate One to One Mapping
    Hibernate One to Many Mapping
    Hibernate Many to Many Mapping

Q: How transaction management works in Hibernate?
A: 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.

Q: What is cascading and what are different types of cascading?
A: When we have relationship between entities, then we need to define how the different operations will affect the other entity. This is done by cascading and there are different types of it.
Here is a simple example of applying cascading between primary and secondary entities.

import org.hibernate.annotations.Cascade;

@Entity
@Table(name = "EMPLOYEE")
public class Employee {
                @OneToOne(mappedBy = "employee")
                @Cascade(value = org.hibernate.annotations.CascadeType.ALL)
                private Address address;
}

Note that Hibernate CascadeType enum constants are little bit different from JPA javax.persistence.CascadeType, so we need to use the Hibernate CascadeType and Cascade annotations for mappings, as shown in above example.
Commonly used cascading types as defined in CascadeType enum are:

None: No Cascading, it’s not a type but when we don’t define any cascading then no operations in     parent affects the child.
    ALL: Cascades save, delete, update, evict, lock, replicate, merge, persist. Basically everything
    SAVE_UPDATE: Cascades save and update, available only in hibernate.
    DELETE: Corresponds to the Hibernate native DELETE action, only in hibernate.
    DETATCH, MERGE, PERSIST, REFRESH and REMOVE – for similar operations
    LOCK: Corresponds to the Hibernate native LOCK action.
    REPLICATE: Corresponds to the Hibernate native REPLICATE action.

Q: How to integrate logQ: logging in hibernate application?
A: Hibernate 4 uses JBoss logging rather than slfQ: used in earlier versions. For logQ: configuration, we need to follow below steps.

Add logQ: 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 logQ: 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 complete example code, you should go through Hibernate logQ: example and Servlet logQ: example.

Q: How to use application server JNDI DataSource with Hibernate framework?
A: 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>
For a complete example, go through Hibernate JNDI DataSource Example.

Q: How to integrate Hibernate and Spring frameworks?
A: Spring is one of the most used Java EE Framework and Hibernate is the most popular ORM framework. That’s why Spring Hibernate combination is used a lot in enterprise applications. The best part with using Spring is that it provides out-of-box integration support for Hibernate with Spring ORM module. Following steps are required to integrate Spring and Hibernate frameworks together.

Add hibernate-entitymanager, hibernate-core and spring-orm dependencies.
Create Model classes and corresponding DAO implementations for database operations. Note that DAO classes will use SessionFactory that will be injected by Spring Bean configuration.
If you are using Hibernate Q: you need to configure org.springframework.orm.hibernate3.LocalSessionFactoryBean or org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean in Spring Bean configuration file. For Hibernate Q: there is single class org.springframework.orm.hibernate4.LocalSessionFactoryBean that should be configured.

Note that we don’t need to use Hibernate Transaction Management, we can leave it to Spring declarative transaction management using @Transactional annotation.
For complete example go through Spring Hibernate Integration and Spring MVC Hibernate Integration.

Q: What is HibernateTemplate class?
A: When Spring and Hibernate integration started, Spring ORM provided two helper classes – HibernateDaoSupport and HibernateTemplate. The reason to use them was to get the Session from Hibernate and get the benefit of Spring transaction management. However from Hibernate 3.0.Q: we can use SessionFactory getCurrentSession() method to get the current session and use it to get the spring transaction management benefits. If you go through above examples, you will see how easy it is and that’s why we should not use these classes anymore.

One other benefit of HibernateTemplate was exception translation but that can be achieved easily by using @Repository annotation with service classes, shown in above spring mvc example. This is a trick question to judge your knowledge and whether you are aware of recent developments or not.

Q: How to integrate Hibernate with Servlet or Struts2 web applications?
A: Hibernate integration with Servlet or Struts2 needs to be done using ServletContextListener, a complete example can be found at Hibernate Struts2 Integration Example.

Q: Which design patterns are used in Hibernate framework?
A: Some of the design patterns used in Hibernate Framework are:
    Domain Model Pattern – An object model of the domain that incorporates both behavior and data.
    Data Mapper – A layer of Mappers that moves data between objects and a database while keeping them independent of each other and the mapper itself.
    Proxy Pattern for lazy loading
    Factory pattern in SessionFactory

Q: What are best practices to follow with Hibernate framework?
A: Some of the best practices to follow in Hibernate are:
Always check the primary key field access, if it’s generated at the database layer then you should not have a setter for this.
By default hibernate set the field values directly, without using setters. So if you want hibernate to use setters, then make sure proper access is defined as @Access(value=AccessType.PROPERTY).
If access type is property, make sure annotations are used with getter methods and not setter methods. Avoid mixing of using annotations on both filed and getter methods.
Use native sql query only when it can’t be done using HQL, such as using database specific feature.
If you have to sort the collection, use ordered list rather than sorting it using Collection API.
Use named queries wisely, keep it at a single place for easy debugging. Use them for commonly used queries only. For entity specific query, you can keep them in the entity bean itself.
For web applications, always try to use JNDI DataSource rather than configuring to create connection in hibernate.
Avoid Many-to-Many relationships, it can be easily implemented using bidirectional One-to-Many and Many-to-One relationships.
For collections, try to use Lists, maps and sets. Avoid array because you don’t get benefit of lazy loading.
Do not treat exceptions as recoverable, roll back the Transaction and close the Session. If you do not do this, Hibernate cannot guarantee that in-memory state accurately represents the persistent state.
Prefer DAO pattern for exposing the different methods that can be used with entity bean
Prefer lazy fetching for associations

Q: What is Hibernate Validator Framework?
A: Data validation is integral part of any application. You will find data validation at presentation layer with the use of Javascript, then at the server side code before processing it. Also data validation occurs before persisting it, to make sure it follows the correct format.
Validation is a cross cutting task, so we should try to keep it apart from our business logic. That’s why JSRQ: and JSRQ: provides specification for validating a bean by using annotations. Hibernate Validator provides the reference implementation of both these bean validation specs. Read more at Hibernate Validation Example.

Q: What is the benefit of Hibernate Tools Eclipse plugin?
A: Hibernate Tools plugin helps us in writing hibernate configuration and mapping files easily. The major benefit is the content assist to help us with properties or xml tags to use. It also validates them against the Hibernate DTD files, so we know any mistakes before hand.


2 comments: