What is hibernate?
Hibernate is a free and Open source Framework. It is widely used light weight ORM Tools for Java Applications. It is written in Java and is Java Virtual Machine (JVM) platform based. It is used to store, manipulate and retrieve data from the database.
[dt_sc_button type=”type1″ link=”http://www.interviewgig.com/discussion-room/post-a-question/” size=”large” bgcolor=”#7ed640″ textcolor=”#ffffff” target=”_blank” timeline_button=”no”]Post a Question[/dt_sc_button]
What is ORM?
ORM is an acronym for Object/Relational mapping. It is a programming strategy to map object with the data stored in the database. It simplifies data creation, data manipulation and data access.
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.
What is Java Persistence API (JPA)?
Java Persistence API (JPA) provides specification for managing the relational data in applications. Current JPA version 2.1 was started in July 2011 as JSR 338. JPA 2.1 was approved as final on 22 May 2013.
JPA specifications are 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?
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.
What are the advantages of Hibernate over JDBC?
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 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.
What is hibernate configuration file?
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.
What is hibernate mapping file?
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.
What are the core interfaces of Hibernate?
The core interfaces of Hibernate framework are:
- Configuration
- SessionFactory
- Session
- Query
- Criteria
- Transaction
What is SessionFactory?
The SessionFactory is a factory of session and client of ConnectionProvider. It holds second level cache (optional) of data. The org.hibernate.SessionFactory interface provides factory method to get the object of Session.
What is Session?
The session object provides an interface between the application and data stored in the database. It is a short-lived object and wraps the JDBC connection. It is factory of Transaction, Query and Criteria. It holds a first-level cache (mandatory) of data. The org.hibernate.Session interface provides methods to insert, update and delete the object. It also provides factory methods for Transaction, Query and Criteria.
What the states of object are in hibernate?
There are 3 states of object (instance) in hibernate.
- Transient: The object is in transient state if it is just created but has no primary key (identifier) and not associated with session.
- Persistent: The object is in persistent state if session is open, and you just saved the instance in the database or retrieved the instance from the database.
- Detached: The object is in detached state if session is closed. After detached state, object comes to persistent state if you call lock() or update() method.
What is Hibernate Session and how to get it?
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.
What is hibernate caching? Explain Hibernate first level cache?
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.
What are different states of an entity bean?
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 ().
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.
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
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 disadvantages 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 is:
- 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 to integrate Hibernate and Spring frameworks?
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 3, you need to configure org.springframework.orm.hibernate3.LocalSessionFactoryBean or org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean in Spring Bean configuration file. For Hibernate 4, 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.
Other Important Hibernate Interview Questions and Answers
What are the important design patterns in Hibernate Framework?
✓ Domain Model Pattern
✓ Data Access Object (DAO)
✓ Abstract Factory
✓ Data Mapper
✓ Proxy
✓ Object-Relational Mapping (ORM)
✓ Query Object
What are different data types supports in Hibernate?
Hibernate data type plays an important role as it acts like a bridge between java types and DB data types.
✓ Primitive types
✓ Date and time types
✓ Binary and large object types
✓ Other JDK-related types
What are the core Interfaces of Hibernate?
Session interface: It allows you to create query objects to retrieve persistent objects.
SessionFactory interface: It is a factory that delivers the session objects to hibernate application.
Configuration interface: It is used to configure and bootstrap hibernate.
Transaction interface: This interface abstracts the code from any kind of transaction implementations such as JDBC transaction, JTA transaction
Query and Criteria interfaces: This interface allows the user to perform queries and also control the flow of the query execution.
Which element is used in hibernate maps java.util.Sorted Map property?
What is the return type of save ()?
What is Criteria object in Hibernate?
It is used to create and execute object-oriented Queries to retrieve the objects.
What is Hibernate tuning?
The process of Hibernate tuning is designed to optimize Hibernate applications’ performance. The three strategies are:
- SQL Optimization
- Session Management
- Data Caching
What is Java Persistence API (JPA)?
JPA stands for Java Persistence API. It provides specification for managing the relational data in applications.
What is HQL?
HQL stands for Hibernate Query Language. It’s very similar to SQL except that we use Objects instead of table names, that makes it closer to object-oriented programming.
What is the benefit of Native SQL query support in hibernate?
Both Hibernate and Java Persistence support queries written in Native SQL It 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 do you know about transaction file?
Transactions denote a work file which can save changes made or revert back the changes. A transaction can be started by session.beginTransaction() and it uses JDBC connection, CORBA or JTA. When this session starts several transactions may occur.
What is the difference between add jar() and add directory() methods?
These methods are the most convenient to use in hibernate. These methods allow you to load all your Hibernate documents at a time. These methods simplify code configuration, refactoring, layout, etc. These functions help you to add your hibernate mapping to Hibernate initialization files.
What are POJOs?
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.
How does hibernate code looks like?
Session session = getSessionFactory().openSession();
Transaction tx = session.beginTransaction();
MyPersistanceClass mpc = new MyPersistanceClass (“Sample App”);
session.save(mpc);
tx.commit();
session.close();
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.
What are the different methods of identifying an object?
✓ Object identity
✓ Object equality
✓ Database identity
What are the ORM levels in hibernate?
Thera are four ORM levels in hibernate.
✓ Pure Relational
✓ Light Object Mapping
✓ Medium Object Mapping
✓ Full Object Mapping
What are the databases that Hibernate supports?
Some database engines supported by Hibernate:
✓ Oracle
✓ MySQL
✓ PostgreSQL
✓ SAP DB
✓ Sybase ASE
✓ H2 Database
✓ Microsoft SQL Server Database
✓ HSQL Database Engine
✓ DB2/NT
✓ Informix Dynamic Server
✓ FrontBase
What is @Transient in Hibernate?
@Transient is one of the Object states. In hibernate which is object relation mapping, it will map or create every variable with the class we have defined.
How would you define automatic dirty checking?
Automatic dirty checking can be defined as a feature that helps us in saving the effort of explicitly asking Hibernate to update the database every time we modify or make changes to the state of an object inside a transaction.
What are the Extension interfaces that are there in hibernate?
There are many extension interfaces provided by hibernate.
✓ ProxyFactory interface: For create proxies
✓ TransactionFactory interface: For transaction management
✓ ConnectionProvider interface: For JDBC connection management
✓ Transaction interface: For transaction management
✓ TransactionManagementLookup interface: For transaction management.
✓ Cahce interface: It provides caching techniques and strategies
✓ CacheProvider interface: same as Cache interface
✓ ClassPersister interface: It provides ORM strategies
✓ IdentifierGenerator interface: For primary key generation
✓ Dialect abstract class: It provides SQL support
How can we bind hibernate session factory to JNDI ?
Hibernate session factory can be bound to JNDI by making configuration changes in hibernate.cfg file.
What are the types of Hibernate instance states?
Three types of instance states:
Transient -It is not associated with any persistence context
Persistent -It is associated with a persistence context
Detached -It was associated with a persistence context which has been closed –currently not associated
What is the main difference between spring and hibernate?
Spring and Hibernate are two different things, Spring has several components like Dependency Injection, Spring MVC, Spring ORM, Spring Rest API. So Spring ORM and Hibernate are kind of similar, they both deal with the object relation model, which means they deal with connection java objects to database entities.
Now if you want to build a Rest API using Spring, you can use the Spring Rest API (Here is the getting start guide for Spring Rest Building a RESTful Web Service) for ORM you can either choose Hibernate or Spring ORM framework in either cases there are advantages and disadvantages but major industry goes with using Hibernate (I might be wrong!!) I’ve used both of them Spring ORM is quite useful in simple scenarios and Hibernate in some complex scenarios, whereas in most complex scenarios both of them are not quite useful when you want to write really complex queries. (Both of them provide functionalities two write queries by yourself in the case of complex scenarios).
Can you explain Query Cache in Hibernate?
Hibernate implements a cache region for queries result set that integrates closely with the hibernate second-level cache.
Query Cache 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");
which property is used to log hibernate generated sql queries in log files?
You can use below property for hibernate configuration to log SQL queries.
<property name="hibernate.show_sql">true</property>
How many ways are used to disable Hibernate’s second-level cache?
There are three ways are used to disable the cache:
By setting hibernate. cache. use_second_level_cache property to false
By using CACHEMODE.IGNORE
By Using a cache provider such as org.hibernate.cache.NoCacheProvider
Which annotation is used to declare a class as a hibernate bean ?
@Entity annotation is used to declare a class as an entity.
For Example :
@Entity
@Table(name="posts")
public class Post{
String title;
String description;
}
Which annotation is used to specify the lazy fetching behavior of a given collection?
@LazyCollection annotation is used to specify the lazy fetching behavior of a given collection.
Which annotation is used to specify the database column used as a ROWID pseudocolumn?
The @RowId annotation is used to specify the database column used as a ROWID pseudocolumn
Which annotation is used to specify an alias for a Hibernate @Filter?
The @SqlFragmentAlias annotation is used to specify an alias for a Hibernate @Filter.
Name the Hibernate Annotations?
- @AccessType
- @AttributeAccessor
- @Any
- @AnyMetaDef
- @AnyMetaDefs
- @BatchSize
- @Cascade
- @Check
- @Cache
- @CollectionId
- @CollectionType
- @ColumnDefault
- @Columns
- @ColumnTransformer
- @ColumnTransformers
- @CreationTimestamp
- @DiscriminatorOptions
- @DiscriminatorFormula
- @DynamicInsert
- @DynamicUpdate
- @Entity
- @Fetch
- @FetchProfile
- @FetchProfile.FetchOverride
- @FetchProfiles
- @Filter
- @Filters
- @FilterDef
- @FilterDefs
- @FilterJoinTable
- @FilterJoinTables
- @ForeignKey
- @Formula
- @Generated
- @GeneratorType
- @GenericGenerator
- @GenericGenerators
- @Immutable
- @Index
- @IndexColumn
- @JoinColumnOrFormula
- @JoinColumnsOrFormulas
- @JoinFormula
- @LazyCollection
- @LazyGroup
- @LazyToOne
- @ListIndexBase
- @Loader
- @ManyToAny
- @MapKeyType
- @MetaValue
- @NamedNativeQueries
- @NamedQueries
- @NamedQuery
- @Nationalized
- @NaturalId
- @NaturalIdCache
- @NotFound
- @OnDelete
- @OptimisticLock
- @OptimisticLocking
- @OrderBy
- @ParamDef
- @Parameter
- @Parent
- @Persister
- @Polymorphism
- @Proxy
- @RowId
- @SelectBeforeUpdate
- @Sort
- @SortComparator
- @SortNatural
- @Source
- @SQLDelete
- @SQLDeleteAll
- @SqlFragmentAlias
- @SQLInsert
- @SQLUpdate
- @Subselect
- @Synchronize
- @Table
- @Tables
- @Target
- @Tuplizer
- @Tuplizers
- @Type
- @TypeDef
- @TypeDefs
- @UpdateTimestamp
- @ValueGenerationType
- @Where
- @WhereJoinTable