Hibernate
Hibernate
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).
Mixing these two models leads to various problems. The common name for these
issues is Object Relational Impedance Mismatch.
Object model and Relational models (RDBMS) have following problems that are
part of Object Relational Impedance Mismatch:
Granularity: Object model is more granular than Relational model. There are more
classes in object model than the corresponding tables in relational model.
Inheritance: Object model supports inheritance. But Relational model does not have
any concept of inheritance.
Identity: Relational model has just one criteria for sameness of data. It is based on
primary key. In object model like Java we can have equals as well as == for
sameness of objects.
Data navigation: In Object model, you can move from one object to another object
for getting data. Egg. you can retrieve and Employee object, then go to its
department object and then get the employees in the department object. In
RDBMS, we try to minimize the SQL calls, so we get all the data by using joins.
214. What are the key characteristics of
Hibernate?
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.
216. How will you map the columns of a DB table to the properties of a
Java class in Hibernate?
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 XML file. 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.
217. Does Hibernate make it mandatory for a mapping file to have
.hbm.xml extension?
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.
POJO stands for Plain Old Java Objects. A POJO is java bean with getter and setter
methods for each property of the bean.
POJO emphasizes the fact that this class is a simple Java class, not a heavy class
like EJB.
POJO also comes with a default constructor that makes it easier to persist with a
default constructor.
220. What is Hibernate Query Language (HQL)?
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.
Hibernate supports executing not only simple queries but also stored procedure of
database. There are three ways to call a stored procedure in Hibernate:
<sql-query name="callEmployeeStoreProcedure">
<return alias="employee" class="com.testHibernate.util.Employee"/>
<![CDATA[CALL GetEmployees(:employeeId)]]> </sql-
query>
</hibernate-mapping>
We can call it with getNamedQuery().
Query query =
session.getNamedQuery("callEmployeeStoreProcedure")
.setParameter("employeeId", “1234”);
List result = query.list();
for(int i=0; i<result.size(); i++){
Employee employee = (Employee)result.get(i);
System.out.println(employee.getEmployeeCode());
}
Native SQL: We can use Native SQL to call a store procedure query directly. In
this example GetEmployees() stored procedure is being called.
Use annotation:
We can also mark out stored procedure with @NamedNativeQueries annotation.
//Employee.java
@NamedNativeQueries({
@NamedNativeQuery(
name = "callEmployeeStoreProcedure", query = "CALL
GetEmployees(:employeeId)", resultClass =
Employee.class )
})
@Entity
@Table(name = "employee")
public class Employee implements java.io.Serializable {
...
Call it with getNamedQuery().
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.
This is a trap question. HibernateTemplate has been deprecated. There were earlier
good reasons to use HibernateTemplate. But now the trend has changed towards
not using it anymore.
To display the SQL generated by Hibernate, we have to turn on the show_sql flag.
<property name=”show_sql”>true</property>
225. What are the different types of collections supported by
Hibernate?
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.
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.
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.
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.
228. How can we get statistics of a SessionFactory in Hibernate?
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 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.
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.
Egg. We can use Callback to get the notification when an object is loaded into or
removed from database.
233. What are the different ORM levels in Hibernate?
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.
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.
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.
236. What are the different types of Association mappings
supported by Hibernate?
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.
239. In Hibernate, how can an object go in Detached
state?
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.
240. How will you order the results returned by a Criteria in
Hibernate?
Hibernate provides an Order criterion that can be used to order the results. This can
be order objects based on their property in ascending or descending order.
Class is org.hibernate.criterion.Order.
Egg.
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.
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.
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();
}
243. How can we mark an entity/collection as immutable
in Hibernate?
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.
Egg.
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
private int id;
We can leave it null/0 while persisting and Hibernate automatically generates a
primary key for us.
Sometimes, AUTO strategy refers to a SEQUENCE instead of an IDENTITY.
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.
248. What are the different second level caches available in
Hibernate?
In Hibernate, we can use different cache providers for implementing second level
cache at JVM/SessionFactory level.
Hashtable
EHCache
OSCache
SwarmCache
JBoss Cache 1.x
JBoss Cache 2
249. Which is the default transaction factory in Hibernate?
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.
In Extra lazy fetching, only individual elements of a collection are fetched from the
database when they are required.
In this strategy, Hibernate does not fetch the whole collection into memory unless it
is essential.
Read only: If an application requires caching only for read but not for write
operations, then we can use this strategy. It is very simple to use and give very
good performance benefit.
Read/Write: If an application also needs caching for write operations, then we use
Read/Write strategy.
Read/write cache strategy should not be used if there is requirement for serializable
transaction isolation level.
Transactional: This strategy supports full transactional cache providers like JBoss
TreeCache.
256. What is the difference between a Set and a Bag in Hibernate?
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.
Let us consider an example in which a customer can have multiple orders and for
every order there has to be a customer.
In OO world, customer is the owner of order. In SQL world, an Order has reference
to customer id.
The inverse side in this mapping is the owner of object. In this case customer is the
owner or order. Since an order cannot exist without a customer. But a customer can
exist without an order.
Also customer has no column to save order data. But an Order table can store
customer id, which is used for mapping.
ORM uses metadata for its internal work. ORM maintains metadata to generate
code used for accessing columns and tables.
ORM maps classes to tables and stores this information in Metadata. It maps fields
in classes to columns in tables. These kinds of mappings are also part of Metadata.
A Named SQL query is the HQL query that is associated with a string name and
can be referenced in the application by name.
@NamedQueries({
@NamedQuery(
name = "findBookByAuthor”,
query = "from Book s where s.author = :author”
)
})
265. What are the two locking strategies in Hibernate?
Just before the commit, we check if any of the resource has changed by another
transaction, then we throw exception and rollback the transaction.
The other transaction can proceed with same resource only after the lock has been
released by previous transaction.
If the version number at the time of write is different than the version number at the
time of read, then we should not commit the transaction.
Table per class hierarchy: In case of multiple types of books, we can have one book
class and one book table. We can store all child classes of book like-
HardCoverBook, PaperBackBook etc in same table book. But we can identify the
subclasses by a BookType column in Book table.
Table per subclass: In this case we can have separate table for each kind of book.
HardCoverBook table for HardCoverBook book class. PaperBackBook table for
PaperBackBook book class. And there will be a parent table, Book for Book class.
Table per concrete class: In this case also we have separate table for each kind of
book. But in this case, we have even inherited properties defined inside each table.
There is no parent table Book for Book class, since it is not a concrete class.