Hibernate Questions


What is Hibernate Framework?
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.

Explain hibernate architecture?
Hibernate architecture comprises of many interfaces such as Configuration, SessionFactory, Session, Transaction, etc.


What is Java Persistence API (JPA)?
Java Persistence API (JPA) provides specification for managing the relational data in applications. JPA specifications is defined with annotations in javax.persistence package. Using JPA annotation helps us in writing implementation independent code.

What are the important benefits of using Hibernate Framework?
1.     Hibernate eliminates all the boiler-plate code that comes with JDBC and takes care of managing resources, so we can focus on business logic.
2.     Hibernate framework provides support for XML as well as JPA annotations, that makes our code implementation independent.
3.     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.
4.     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.
5.     Hibernate supports lazy initialization using proxy objects and perform actual database queries only when it’s required.
6.     Hibernate cache helps us in getting better performance.
7.     For database vendor specific feature, hibernate is suitable because we can also execute native sql queries.

What are best practices to follow with Hibernate framework?
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

What are the advantages of Hibernate over JDBC?
Some of the important advantages of Hibernate framework over JDBC are:
1.     Hibernate removes a lot of boiler-plate code that comes with JDBC API, the code looks more cleaner and readable.
2.     Hibernate supports inheritance, associations and collections. These features are not present with JDBC API.
3.     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.
4.     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.
5.     Hibernate Query Language (HQL) is more object oriented and close to java programming language. 
6.     Hibernate supports caching that is better for performance, JDBC queries are not cached hence performance is low.
7.     Hibernate provide option through which we can create database tables too, for JDBC tables must exist in the database.
8.     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.
9.     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.

Name some important interfaces of Hibernate framework?
Some of the important interfaces of Hibernate framework are:
1.     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.
2.     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.
3.     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:
1.     javax.persistence.Entity: Used with model classes to specify that they are entity beans.
2.     javax.persistence.Table: Used with entity beans to define the corresponding table name in database.
3.     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.
4.     javax.persistence.Id: Used to define the primary key in the entity bean.
5.     javax.persistence.EmbeddedId: Used to define composite primary key in the entity bean.
6.     javax.persistence.Column: Used to define the column name in database table.
7.     javax.persistence.GeneratedValue: Used to define the strategy to be used for generation of primary key. Used in conjunction with javax.persistence.GenerationType enum.
8.     javax.persistence.OneToOne: Used to define the one-to-one mapping between two entity beans. We have other similar annotations as OneToManyManyToOne and ManyToMany
9.     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
10.  javax.persistence.PrimaryKeyJoinColumn: Used to define the property for foreign key. Used with org.hibernate.annotations.GenericGenerator and org.hibernate.annotations.Parameter

@Entity
@Table(name = "PERSON")
@Access(value=AccessType.FIELD)
public class Person {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "per_id")
private long id;

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

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

//getter setter methods
}

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

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

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

@OneToOne
@PrimaryKeyJoinColumn
private Person person;

//getter setter methods
}


What is Hibernate SessionFactory and how to configure it?
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.

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.
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.

What is difference between Hibernate Session get() and load() method?
1.     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.
2.     Since load() throws exception when data is not found, we should use it only when we know data exists.

What is hibernate caching? Explain Hibernate first level cache?
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.

What are different ways to disable hibernate second level cache?
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

What are different states of an entity bean?
An entity bean instance can exist is one of the three states.
1.     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().
2.     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.
3.     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().

What is difference between Hibernate save(), saveOrUpdate() and persist() methods?
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.

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

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

What are the collection types in Hibernate?
There are five collection types in hibernate used for one-to-many relationship mappings.
1.     Bag
2.     Set
3.     List
4.     Array
5.     Map

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.

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 is the benefit of Hibernate Criteria API?
Hibernate provides Criteria API that is more object oriented for querying the database and getting results. 
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.

What is cascading and what are different types of cascading?
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.

@Entity
@Table(name = "EMPLOYEE")
public class Employee {

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

Commonly used cascading types as defined in CascadeType enum are:
1.     None: No Cascading, it’s not a type but when we don’t define any cascading then no operations in parent affects the child.
2.     ALL: Cascades save, delete, update, evict, lock, replicate, merge, and persist. Basically everything
3.     SAVE_UPDATE: Cascades save and update, available only in hibernate.
4.     DELETE: Corresponds to the Hibernate native DELETE action, only in hibernate.
5.     DETATCH, MERGE, PERSIST, REFRESH and REMOVE – for similar operations
6.     LOCK: Corresponds to the Hibernate native LOCK action.
7.     REPLICATE: Corresponds to the Hibernate native REPLICATE action.
   
What are the benefits of using Hibernate template?
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.

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

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

What is N+1 SELECT problem in Hibernate? 
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.

What are some strategies to solve the N+1 SELECT problem in Hibernate? 
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 the N+1 problem to N/K + 1 problem where K is the size of the batch
2) subselect fetching strategy
3) disabling lazy loading




No comments:

Post a Comment