What are the advantages of Hibernate over JDBC? (detailed answer)
Apart from Persistence i.e. saving and loading data from Database, Hibernate also provides following benefits
1) Caching
2) Lazy Loading
3) Relationship management and provides code for mapping an object to the data
4) The developer is free from writing code to load/store data into the database.
Difference between get() vs load() method in Hibernate? (detailed answer)
This is one of the most frequently asked Hibernate interview question, I have seen it several times. The key difference between get() and load() method is that load() will throw an exception if an object with id passed to them is not found, but get() will return null. Another important difference is that load can return proxy without hitting the database unless required (when you access any attribute other than id) but get() always go to the database, so sometimes using load() can be faster than the get() method. It makes sense to use the load() method if you know the object exists but get() method if you are not sure about object's existence.
What is N+1 SELECT problem in Hibernate? (detailed answer)
The N+1 SELECT problem is a result of lazy loading and load on demand fetching strategy. In this case, Hibernate ends up executing N+1 SQL queries to populate a collection of N elements. For example, if you have a List of N Items where each Item has a dependency on a collection of Bid object. Now if you want to find the highest bid for each item then Hibernate will fire 1 query to load all items and N subsequent queries to load Bid for each item. So in order to find the highest bid for each item your application end up firing N+1 queries. It's one of the important Hibernate interview questions and I suggest to read chapter 13 of Java Persistence with Hibernate to understand this problem in more details.
What are some strategies to solve the N+1 SELECT problem in Hibernate? (detailed answer)
This is the follow-up question of previous Hibernate interview question. If you answer the last query correctly then you would be most likely asked this one. Here are some strategies to solve the N+1 problem:
1) pre-fetching in batches, this will reduce N+1 problem to N/K + 1 problem where K is size of batch
2) subselect fetching strategy
3) disabling lazy loading
What is the difference between save() and persist() method in Hibernate? (detailed answer)
Main difference between save() and persist() method is that, save returns a Serializable object while return type of persist() method is void, so it doesn't return anything. Here is a nice diagram which explains the state transition in Hibernate:
What is the requirement for a Java object to become Hibernate entity object?
It should not be final and must provide a default, no-argument constructor. Becasue
hibernate uses reflection Class<T>.newInstance() to create a new instance of your classes and reflection requiring a no-arg constructor.
hibernate uses reflection Class<T>.newInstance() to create a new instance of your classes and reflection requiring a no-arg constructor.
What are different types of caches available in Hibernate? (detailed answer)
This is another common Hibernate interview question. Hibernate provides the out-of-box caching solution but there are many caches e.g. first level cache, second level cache and query cache. First level cache is maintained at Session level and cannot be disabled but the second level cache is required to be configured with external cache provider like EhCache.
What is the difference between first and second level cache in Hibernate? (detailed answer)
This is again follow-up of previous Hibernate interview question. The first level cache is maintained at Session level while the second level cache is maintained at SessionFactory level and shared by all sessions. You can read these books to learn more about caching in Hibernate.
Does Hibernate Session interface is thread-safe in Java? (detailed answer)
No, Session object is not thread-safe in Hibernate and intended to be used with-in single thread in the application.
Does SessionFactory is thread-safe in Hibernate? (detailed answer)
SessionFactory is both Immutable and thread-safe and it has just one single instance in Hibernate application. It is used to create Session object and it also provide caching by storing SQL queries stored by multiple session. The second level cache is maintained at SessionFactory level. This can be a difficult and tricky question for less experienced Java developers who are not familiar with thread-safety and Immutability.
What is different between Session and Sessionfactory in Hibernate? (detailed answer)
This is another popular Hibernate interview question, mostly at a telephonic round of interviews. The main difference between Session and SessionFactory is that former is a single-threaded, short-lived object while later is Immutable and shared by all Session. It also lives until the Hibernate is running. Another difference between Session and SessionFactory is that former provides first level cache while SessionFactory provides the Second level cache.
What is criterion query in hibernate? (detailed answer)
Criteria is a simplified API for retrieving entities by composing Criterion objects also known as Criterion query. This is a very convenient approach for functionality like "search" screens where you can filter data on multiple conditions as shown in the following example:
List books = session.createCriteria(Book.class)
.add(Restrictions.like("name", "java%") )
.add(Restrictions.like("published_year", "2015"))
.addOrder(Order.asc("name") )
.list();
This can be a tough question if you are not using Hibernate on a daily basis, I have interviewed several Java developers who have used Hibernate but doesn't know about Criterion query or API.
What are other ORM frameworks? Any alternative of Hibernate?
This is a general question, sometimes asked to start the conversation and other times to finish the interview. EJB and TopLink from Oracle are two of the most popular alternative to Hibernate framework.
What is the difference between save() and saveOrUpdate() method of Hibernate? (detailed answer)
Though both save() and saveOrUpdate() method is used to store object into Database, the key difference between them is that save can only INSERT records but saveOrUpdate() can either INSERT or UPDATE records.
What is difference between getCurrentSession() and openSession() in Hibernate? (detailed answer)
An interesting Hibernate interview question as you might have used both getCurrentSession() and openSession() to obtain an instance of Session object. I have left this question unanswered for you to answer or find an answer based on your experience.
What is Hibernate Query Language (HQL)? (detailed answer)
Hibernate query language, HQL is an object-oriented extension to SQL. It allows you to query, store, update, and retrieve objects from a database without using SQL. This question is also similar to the earlier question about Criterion query, Java developers who have not used Hibernate extensively will not know much about features like HQL and Criterion.
When do you use merge() and update() in Hibernate?
This is one of the tricky Hibernate interview questions. You should use update() if you are sure that the Hibernate session does not contain an already persistent instance with the same id and use merge() if you want to merge your modifications at any time without considering the state of the session. See Java Persistence with Hibernate for more details.
The difference between sorted and ordered collection in Hibernate?
The main difference between sorted and ordered collection is that sorted collection sort the data in JVM's heap memory using Java's collection framework sorting methods while ordered collection is sorted using order by clause in the database itself. A sorted collection is more suited for small dataset but for a large dataset, it's better to use ordered collection to avoid OutOfMemoryError in Java application.
How do you log SQL queries issued by the Hibernate framework in Java application?
You can use the show_sql property to log SQL queries issued by the Hibernate framework, Just add the following line in your Hibernate configuration file:
<property name=”show_sql”> true </property>
What are the three states of a Hibernate Persistence object can be? (detailed answer)
The Hibernate persistent or entity object can live in following three states:
1) transient
2) persistent
3) detached
What is the difference between the transient, persistent and detached state in Hibernate? (detailed answer)
New objects created in Java program but not associated with any hibernate Session are said to be in the transient state. On the other hand, an object which is associated with a Hibernate session is called Persistent object. While an object which was earlier associated with Hibernate session but currently it's not associate is known as a detached object. You can call save() or persist() method to store those object into the database and bring them into the Persistent state. Similarly, you can re-attach a detached object to hibernate sessions by calling either update() or saveOrUpdate() method.
Which cache is used by Session Object in Hibernate? First level or second level cache? (detailed answer)
A Session object uses the first-level cache. As I told before the second level cache is used at SessionFactory level. This is a good question to check if Candidate has been working in hibernate or not. If he has not worked in Hibernate from a long time then he would get confused in this question.
Name some important interfaces of Hibernate framework?
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.
Name some important annotations used for Hibernate mapping?
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 beans. We have other similar annotations as OneToMany, ManyToOne and ManyToMany
org.hibernate.annotations.Cascade: Used to define the cascading between two entity beans, used 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.
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
}
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
}
What is difference between openSession and getCurrentSession?
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,
How to configure Hibernate Second Level Cache using EHCache?
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 myehcache.xml would look like below.
<?xml version="1.0" 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="10000" eternal="false"
timeToIdleSeconds="120" timeToLiveSeconds="120" diskSpoolBufferSizeMB="30"
maxEntriesLocalDisk="10000000" diskExpiryThreadIntervalSeconds="120"
memoryStoreEvictionPolicy="LRU" statistics="true">
<persistence strategy="localTempSwap" />
</defaultCache>
<cache name="employee" maxEntriesLocalHeap="10000" eternal="false"
timeToIdleSeconds="5" timeToLiveSeconds="10">
<persistence strategy="localTempSwap" />
</cache>
<cache name="org.hibernate.cache.internal.StandardQueryCache"
maxEntriesLocalHeap="5" eternal="false" timeToLiveSeconds="120">
<persistence strategy="localTempSwap" />
</cache>
<cache name="org.hibernate.cache.spi.UpdateTimestampsCache"
maxEntriesLocalHeap="5000" 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 {
}
What are the collection types in Hibernate?
There are five collection types in hibernate used for one-to-many relationship mappings.
Bag
Set
List
Array
Map
Why we should not make Entity Class final?
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.
Can we execute native sql query in hibernate?
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.
What is the benefit of native sql query support in hibernate?
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.
What is Named SQL Query?
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.
What are the benefits of Named SQL Query?
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.
What is the benefit of Hibernate Criteria API?
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.
How transaction management works in Hibernate?
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.
What is Hibernate proxy?
Mapping of classes can be made into a proxy instead of a table. A proxy is
returned when actually a load is called on a session. The proxy contains
actual method to load the data. The proxy is created by default by
Hibernate, for mapping a class to a file. The code to invoke JDBC is
contained in this class.
Read More: https://www.journaldev.com/3633/hibernate-interview-questions-and-answers
No comments:
Post a Comment