Hibernate Interview Questions


Question: - What is Session in Hibernate?
Answer: - Session is an interface in hibernate. We can get Session objects using SessionFactory references. Session is a wrapper for “java.sql.Connection”. It performs manipulation on DB entities. This is the basic interface for hibernate framework. Session object is light weight and can be created and destroyed without expensive process. It is short lived object and not thread safe. It works as a factory for “org.hibernate.Transaction”. It maintains the first level cache by default and this can be used while searching for the objects using identifier.

Question: - What session.refresh() method will do?
Answer: - session.refresh():- During the bulk update to the DB with hibernate, the changes made are not replicated to the entities stored in the current session. So calling session.refresh will load the modifications to session entities.

Question: - What session.flush () method will do?
Answer: - session.flush ():- This tells Hibernate to execute the SQL statements needed to synchronize the JDBC connection's state with the state of objects held in the session-level cache. session.flush () call will save the object instances to the database.



Question: - What session.clear () method will do?
Answer: - session.clear():- session.clear() method call can be used to clear the persistance context. It completely clears the session. This method call evicts all the objects from the session.

Question: - What session.evict (Object obj) method will do?
Answer: - session.evict(Object object): This method call will remove the instance that is passed as an argument in the evict method from the session cache and make a persistent object as a detached object.

Question: - What session.save() method will do?
Answer: - session.save() : This method call does an insert and will fail if the primary key is already available.

Question: - What session.saveOrUpdate() method will do?
Answer: - session.saveOrUpdate() : This method call does a select first to determine if it needs to do an insert or an update. Insert data if primary key is not already available in database otherwise do update data.

Question: - What session.persist () method will do?
Answer: - session.persist() : This method call does the same like session.save().
But session.save() returns Serializable object but session.persist() returns void.
session.save() returns the generated identifier (Serializable object) and session.persist() doesn’t.

Question: - What session.delete() method will do?
Answer: - session.delete(Object obj):- This method call will remove a persistent instance from the datastore.

Question: - What are the Fetching Strategies in hibernate?
Answer: -Fetching Strategies
Below are the fetching strategies.

1. fetch-”join” = this disable the lazy loading, always load all the collections and entities.
2. fetch-”select” (default) = this will lazily load all the collections and entities.
3. fetch-”subselect” = this will group its collection into a sub select statement.

Note: - These stretegies we can use in FetchMode.

Question: - What is Lazy and Eager loading strategies?
Answer: - The EAGER strategy is a hint given to the persistence provider that at runtime the data must be eagerly fetched (fetch in one query).
The LAZY strategy is a hint given to the persistence provider that at runtime the data should be fetched lazily when it is first accessed (fetch when needed as sub-queries).
 EAGER Fetch — get results in one query ( parent and child both )
LAZY Fetch – get results as sub-query.
For Example:
Suppose we have an entity called Student and another entity called Department.
The Student entity might have some basic properties such as id, name etc. as well as a property called Department.
Now Using Eager Loading, when we load a Student from the database, Hibernate will load student id, name fields and it also loads related Department details using the getDepartment() method -This is called  eager loading.
When a Student is associated with many Departments then it is not efficient to load its entire Department because it will create overhead on performance as they are not needed. So in such cases, we can declare that we want Department to be loaded when they are actually needed. This is called lazy loading.

Questions: - What is the use of inverse in Hibernate?
Answer: - The “inverse” keyword is always declare in one-to-many and many-to-many relationship. We
don’t have “inverse” keyword in many-to-one relationship. “inverse” is used to decide which side is the relationship owner will manage the relationship (insert or update of the foreign key column). It means which side is responsible to take care of the relationship.

inverse = “true” describes that this is the relationship owner, where as inverse=”false” (default) means it’s not the relationship owner.

Questions: - What is the use of cascade in Hibernate?
Answer: -

Cascade values are
none (default)
save
update
save-update
delete
all
all-delete-orphan

If cascade = “none” and if we execute save (or update or delete) operation on parent class object, then child class objects will not be effected.

If we write cascade = “all”, then the operations like save or delete or update executed at parent class object will be effected to child class object also.

If we write cascade = “save-update”, then the operations like save and update executed at parent class object will also be effected to child class object also.

In an application, if a child record is removed from the collection and if we want to remove that child record immediately from the database, then we need to set the cascade =”all-delete-orphan”

Questions: - What is the use of BAG collection in hibernate?
Answer: - If our table does not have an index column, and we want to use collection property type, then in this case we can use <bag> Collection property in Hibernate. When a collection of data is retrieved and assigned to bag collection then bag does not retain its order but it can be optionally sorted or ordered. A bag permit duplicates it means it does not have primary key. So finally we can tell that a bag is an unordered, unkeyed collection that can contain the same element multiple times.

Questions: - What is optimistic locking in Hibernate?
Answer: - When we load object in one transaction, modify the data and save it later in another transaction then in this situation Hibernate optimistic locking works. This locking ensures that some other transaction hasn’t changed that same object in the database in between. However, optimistic locking doesn't affect isolation of concurrent transactions.



Questions: - What is transcriptional write behind in Hibernate?
Answer: - When we call session.save(Object) in the hibernate code then it does not fire the SQL insert query immediately. Similarly when we call session.delete(Object) or session.update(Object)  then it will not fire the corresponding SQL queries(delete and update queries) immediately.

The meaning is that when objects associated with persistence context are modified, the changes are not immediately propagated to the database.

Hibernate collects all such database operations associated with a transaction and create minimum set of SQL queries and execute them. This will provide us 2 advantages:-

In case of multiple updates or inserts or deletes, Hibernate is able to make use of the JDBC Batch API to optimize performance.
Every property change in the object does not cause a separate SQL update query to be executed.
Avoiding unwanted SQL queries ensures minimum hits to database thus reducing the network latency.
This delayed execution of sql queries is known as transnational write behind.

Questions: - What’s Hibernate?
Answer: 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.

Questions: - What is ORM?
Answer: 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.

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

Questions: - What’s the usage of Configuration Interface in hibernate?
Answer: 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.

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

Questions: -  Should all the mapping files of hibernate have .hbm.xml extension to work properly?
Answer: 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.

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

Questions: - What’s HQL?
Answer: 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.

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

Questions: - What are the benefits of using Hibernate template?
Answer: Following are some key benefits of using Hibernate template:
 Session closing is automated.
 Interaction with hibernate session is simplified.
 Exception handling is automated.

Questions: - How can we see hibernate generated SQL on console?
Answer: We need to add following in hibernate configuration file to enable viewing SQL on the console for debugging purposes:
<property name=”show_sql”>true</property>

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

Questions: - What the benefits are of hibernate over JDBC?
Answer: 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.
 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.
 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.

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

Questions: - What is transient instance state in Hibernate?
Answer: 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.

Questions: - How can we reduce database write action times in Hibernate?
Answer: 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.

Questions: - What’s the usage of callback interfaces in hibernate?
Answer: 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.

Questions: - When an instance goes in detached state in hibernate?
Answer: 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.

Questions: - What the four ORM levels are in hibernate?
Answer: Following are the four ORM levels in hibernate:
> Pure Relational
> Light Object Mapping
> Medium Object Mapping
> Full Object Mapping

Reference:
Hibernate.org/orm/

Put your question, if you have any so that I'll try to answer it...

1 comment: