Hibernate Flashcards

1
Q

What is Hibernate framework?

A

Hibernate is a popular Object Relational Mapping (ORM)
framework of Java. It helps in mapping the Object Oriented Domain
model to Relational Database tables.
Hibernate is a free software distributed under GNU license.
Hibernate also provides implementation of Java Persistence API
(JPA).
In simple words, it is a framework to retrieve and store data from
database tables from Java.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

What is an Object Relational Mapping (ORM)?

A

Object Relational Mapping (ORM) is a programming technique to
map data from a relational database to Object oriented domain
model. This is the core of Hibernate framework.
In case of Java, most of the software is based on OOPS design. But
the data stored in Database is based on Relation Database
Management System (RDBMS).
ORM helps in data retrieval in an Object Oriented way from an
RDBMS. It reduces the effort of developers in writing queries to
access and insert data

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

What is the purpose of Configuration Interface in

Hibernate?

A

Configuration interface can be implemented in an application to specify the properties and mapping documents for creating a SessionFactory in Hibernate.

By default, a new instance of Configuration uses properties mentioned in hibernate.properties file.
Configuration is mainly an initialization time object that loads the
properties in helps in creating SessionFactory with these properties.
In short, Configuration interface is used for configuring Hibernate
framework in an application.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

hat is Object Relational Impedance Mismatch?

A

Object Relational Impedance Mismatch (ORIM) is also known as paradigm mismatch. It means that Object model and Relational
model do not work well with each other.

Relational model or a RDBMS represents data in tabular format like a spreadsheet. Object model or OOPS represents the data as an inter-connected graph of objects.

Mixing these two models leads to various problems. The common name for these issues is Object Relational Impedance Mismatch.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

What are the key characteristics of Hibernate?

A

Object/Relational Mapping (ORM): Hibernate provides ORM
capabilities to developers. So then can write code in Object model
for connecting with data in Relational model.
JPA Provider: Hibernate provides an excellent implementation of
Java Persistence API (JPA) specification.
Idiomatic persistence: Hibernate provides persistence based on
natural Object-oriented idioms with full support for inheritance,
polymorphism, association, composition, and the Java collections
framework. It can work with any data for persistence.
High Performance: Hibernate provides high level of performance
supporting features like- lazy initialization, multiple fetching
strategies, optimistic locking etc. Hibernate does not need its own
database tables or fields. It can generate SQL at system
initialization to provide better performance at runtime.
Scalability: Hibernate works well in multi server clusters. It has
built in scalability support. It can work well for small projects as
well as for large business software.
Reliable: Hibernate very reliable and stable framework. This is the
reason for its worldwide acceptance and popularity among
developer community.
Extensible: Hibernate is quite generic in nature. It can be configured
and extended as per the use case of application.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

Can you tell us about the core interfaces of Hibernate framework?

A

Configuration: Configuration interface can be implemented in an
application to specify the properties and mapping documents for
creating a SessionFactory in Hibernate. Hibernate application
bootstraps by using this interface.
SessionFactory: In Hibernate, SessionFactory is used to create and
manage Sessions. Generally, there is one SessionFactory created for
one database. It is a thread-safe interface that works well in multithreaded applications.
Session: Session is a lightweight object that is used at runtime
between a Java application and Hibernate. It contains methods to
create, read and delete operations for entity classes. It is a basic
class that abstracts the concept of persistence.
Transaction: This is an optional interface. It is a short lived object
that is used for encapsulating the overall work based on unit of
work design pattern. A Session can have multiple Transactions.
Query: This interface encapsulates the behavior of an objectoriented query in Hibernate. It can accept parameters and execute
the queries to fetch results. Same query can be executed multiple
times.
Criteria: This is a simplified API to retrieve objects by creating
Criterion objects. It is very easy to use for creating Search like
features.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

How will you map the columns of a DB table to the properties of a Java class in Hibernate?

A

We can map the class properties and table columns by using one of
the two ways:
XML: We can map the column of a table to the property of a class in
XMLfile. It is generally with extension hbm.xml
Annotation: We can also use annotations @Entity and @Table to
map a column to the property of a class.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

What are the steps for creating a SessionFactory in Hibernate?

A

Steps to create a SessionFactory in Hibernate are:
Configuration: First create a Configuration object. This will refer to
the path of configuration file.
Resource: Add config file resource to Configuration object.
Properties: Set properties in the Configuration object.
SessionFactory: Use Configuration object to build SessionFactory.
Egg.
Configuration config = new Configuration();
config.addResource(“testInstance/configuration.hbm.xml”);
config.setProperties( System.getProperties() );
SessionFactory sessions = config.buildSessionFactory();

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

Why do we use POJO in Hibernate?

A

POJO stands for Plain Old Java Objects. A POJO is java bean with
getter and setter methods for each property of the bean.
It is a simple class that encapsulates an object’s properties and
provides access through setters and getters.
Some of the reasons for using POJO in Hibernate are:
POJO emphasizes the fact that this class is a simple Java class, not
a heavy class like EJB.
POJO is a well-constructed class, so it works well with Hibernate
proxies.
POJO also comes with a default constructor that makes it easier to
persist with a default constructor.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

What is Hibernate Query Language (HQL)?

A

Hibernate Query Language is also known as HQL. It is an Object
Oriented language. But it is similar to SQL.
HQL works well with persistent objects and their properties. HQL
does not work on database tables.
HQL queries are translated into native SQL queries specific to a
database.
HQL supports direct running of native SQL queries also. But it
creates an issue in Database portability

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

What is Criteria API in Hibernate?

A

Criteria is a simplified API in Hibernate to get entities from database by creating Criterion objects.

It is a very intuitive and convenient approach for search features.

Users can specify different criteria for searching entities and Criteria API can handle these.
Criterion instances are obtained through factory methods on Restrictions.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

What are the different types of

collections supported by Hibernate?

A

Indexed Collections: List and Maps

Sorted Collections: java.util.SortedMap and java.util.SortedSet

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

What is the difference between
session.save() and
session.saveOrUpdate() methods in
Hibernate?

A

Save method first stores an object in the database. Then it persists
the given transient instance by assigning a generated identifier.
Finally, it returns the id of the entity that is just created.
SaveOrUpdate() method calls either save() or update() method. It
selects one of these methods based on the existence of identifier.
If an identifier exists for the entity then update() method is called. If
there is no identifier for the entity then save() method is called as
mentioned earlier.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

What are the advantages of

Hibernate framework over JDBC?

A

Database Portability: Hibernate can be used with multiple types of
database with easy portability. In JDBC, developer has to write
database specific native queries. These native queries can reduce
the database portability of the code.
Connection Pool: Hibernate handles connection pooling very well.
JDBC requires connection pooling to be defined by developer.
Complexity: Hibernate handles complex query scenarios very well
with its internal API like Criteria. So developer need not gain
expertise in writing complex SQL queries. In JDBC application
developer writes most of the queries.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q

What is the Transient state of an object in Hibernate?

A

When an object is just instantiated using the new operator but is not
associated with a Hibernate Session, then the object is in Transient
state.
In Transient state, object does not have a persistent representation
in database. Also there is no identifier assigned to an object in
Transient state.
An object in Transient state can be garbage collected if there is no
reference pointing to it

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

What is the Detached state of an object in Hibernate?

A

An object is in detached state if it was persistent earlier but its
Session is closed now.
Any reference to this object is still valid. We can even update this
object. Later on we can even attach an object in detached state to a
new session and make it persistent.
Detached state is very useful in application transactions where a
user takes some time to finish the work.

17
Q

What is the use of Dirty Checking in Hibernate?

A

Dirty Checking is very useful feature of Hibernate for write to
database operations. Hibernate monitors all the persistent objects
for any changes. It can detect if an object has been modified or not.
By Dirty Checking, only those fields of an object are updated that
require any change in them. It reduces the time-consuming database
write operations

18
Q

What is the purpose of Callback interface in Hibernate?

A

Callback interface in Hibernate is mainly used for receiving notifications of different events from an object.

Egg. We can use Callback to get the notification when an object is
loaded into or removed from database.

19
Q

What are the different ORM levels in Hibernate?

A

Pure Relational ORM: At this level entire application is designed around the relational model. All the operations are SQL based at
this level.

Light Object Mapping: At this level entity classes are mapped manually to relational tables. Business logic code is hidden from data access code. Applications with less number of entities use this level.
Medium Object Mapping: In this case, application is designed around an object model. Most of the SQL code is generated at compile time. Associations between objects are supported by the persistence mechanism. Object-oriented expression language is used to specify queries.

Full Object Mapping: This is one of the most sophisticated object modeling level. It supports composition, inheritance, polymorphism
and persistence. The persistent classes do not inherit any special base class at this level. There are efficient fetching and caching strategies implemented transparently to the application
20
Q

What is Query Cache in Hibernate?

A

Hibernate provides Query Cache to improve the performance of queries that run multiple times with same parameters.

At times Query Caching can reduce the performance of Transactional processing. By default Query Cache is disabled in Hibernate.

It has to be used based on the benefits gained by it in performance of the queries in an application.

21
Q

What is Unit of Work design pattern?

A

A Unit of Work is a list of ordered operations that we want to run on a database together. Either all of these go together or none of these goes.

Most of the time, we use term business transaction in place of Unit of Work.

Egg. In case of money transfer from account A to B, the unit of work can be two operation Debit account A and Credit account B in a sequence. Both these operations should happen together and in right
sequence

22
Q

In Hibernate, how can an object go in Detached state?

A

Once the session attached to an Object is closed, the object goes
into Detached state. An Object in Detached state can be attached to
another session at a later point of time.
This state is quite useful in concurrent applications that have long
unit of work

23
Q

How does Example criterion work in Hibernate?

A

In Hibernate, we can create an object with desired properties. Then
we can use this object to search for objects with similar object. For
this we can use org.hibernate.criterion.Example criterion.
Egg. First we create a sample book object of author Richard and
category mystery. Then we search for similar books.
Book book = new Book();
book.setAuthor(‘Richard’);
book.setCategory(Category.MYSTERY);
List results = session.createCriteria(Book.class)
.add( Example.create(book) )
.list();

24
Q

How does Transaction management work in Hibernate?

A
In Hibernate we use Session interface to get a new transaction.
Once we get the transaction we can run business operations in that
transaction. At the end of successful business operations, we
commit the transaction. In case of failure, we rollback the
transaction.
Sample code is a follows:
Session s = null;
Transaction trans = null;
try {
s = sessionFactory.openSession();
trans = s.beginTransaction();
doTheAction(s);
trans.commit();
} catch (RuntimeException exc) {
trans.rollback();
} finally {
s.close();
}
25
Q

How can we mark an entity/collection as immutable in Hibernate?

A

In Hibernate, by default an entity or collection is mutable. We can
add, delete or update an entity/collection.
To mark an entity/collection as immutable, we can use one of the
following:
@Immutable: We can use the annotation @Immutable to mark an
entity/collection immutable.
XML file: We can also set the property mutable=false in the XML
file for an entity to make it immutable

26
Q

What are the different options
to retrieve an object from database in
Hibernate?

A

In Hibernate, we can use one of the following options to retrieve
objects from database:
Identifier: We can use load() or get() method and pass the identifier
like primary key to fetch an object from database.
HQL: We can create a HQL query and get the object after executing
the query.
Criteria API: We can use Criteria API to create the search
conditions for getting the objects from database.
Native SQL: We can write native SQL query for a database and just
execute it to get the data we want and convert it into desired object.

27
Q

What is the first level of cache in Hibernate?

A

A Hibernate Session is the first level of cache for persistent data in a transaction.

The second level of cache is at JVM or SessionFactory level.

28
Q

What are the different second level caches available in Hibernate?

A
In Hibernate, we can use different cache providers for implementing
second level cache at JVM/SessionFactory level.
Some of these are:
Hashtable
EHCache
OSCache
SwarmCache
JBoss Cache 1.x
JBoss Cache 2
29
Q

Which is the default transaction factory in Hibernate?

A

In Hibernate, default transaction factory is

JDBCTransactionFactory. But we can change it by setting the property hibernate.transaction.factory_class.

30
Q

What are the different fetching strategies in Hibernate?

A

Hibernate 3 onwards there are following fetching strategies to retrieve associated objects:

Join fetching: In Join strategy Hibernate uses OUTER join to retrieve the associated instance or collection in the same SELECT.

Select fetching: In Select strategy, Hibernate uses a second SELECT to retrieve the associated entity or collection. We can explicitly
disable lazy fetching by specifying lazy=”false”. By default lazy fetching is true.

Subselect fetching: In Subselect strategy, Hibernate uses a second
SELECT to retrieve the associated collections for all entities
retrieved in a previous query or fetch.

Batch fetching: In Batch strategy, Hibernate uses a single SELECT to retrieve a batch of entity instances or collections by specifying a
list of primary or foreign keys. This is a very good performance optimization strategy for select fetching.

31
Q

What is the difference between Immediate fetching and Lazy collection fetching?

A

In Immediate fetching an association, collection or attribute is retrieved at the same time when the owner is loaded.

But in Lazy collection fetching, a collection is fetched only when an operation is invoked on that collection by client application.

This is the default fetching strategy for collections in Hibernate.
Lazy fetching is better from performance perspective.

32
Q

What is the difference between a Set and a Bag in Hibernate?

A

A Bag in Hibernate is an unordered collection. It can have duplicate elements. When we persist an object in a bag, there is no guarantee that bag will maintain any order.

A Set in Hibernate can only store unique objects. If we add the same element to set second time, it just replaces the old one. By default a
Set is unordered collection in Hibernate.