Wednesday, October 15, 2008

Hibernate Interview Questions

How will you configure Hibernate?

Answer: The configuration files hibernate.cfg.xml (or hibernate.properties) and mapping files *.hbm.xml are used by the Configuration class to create (i.e. configure and bootstrap hibernate) the SessionFactory, which in turn creates the Session instances. Session instances are the primary interface for the persistence service.

hibernate.cfg.xml (alternatively can use hibernate.properties): These two files are used to configure the hibernate sevice (connection driver class, connection URL, connection username, connection password, dialect etc). If both files are present in the classpath then hibernate.cfg.xml file overrides the settings found in the hibernate.properties file.

Mapping files (*.hbm.xml): These files are used to map persistent objects to a relational database. It is the best practice to store each object in an individual mapping file (i.e mapping file per class) because storing large number of persistent classes into one mapping file can be difficult to manage and maintain. The naming convention is to use the same name as the persistent (POJO) class name. For example Account.class will have a mapping file named Account.hbm.xml. Alternatively hibernate annotations can be used as part of your persistent class code instead of the *.hbm.xml files.

What is a SessionFactory? Is it a thread-safe object?

Answer:SessionFactory is Hibernate’s concept of a single datastore and is threadsafe so that many threads can access it concurrently and request for sessions and immutable cache of compiled mappings for a single database.
A SessionFactory is usually only built once at startup. SessionFactory should be wrapped in some kind of singleton so that it can be easily accessed in an application code. SessionFactory sessionFactory = new Configuration().configure().buildSessionfactory();

What is a Session? Can you share a session object between different theads?

Answer:Session is a light weight and a non-threadsafe object (No, you cannot share it between threads) that represents a single unit-of-work with the database. Sessions are opened by a SessionFactory and then are closed when all work is complete.
Session is the primary interface for the persistence service. A session obtains a database connection lazily (i.e. only when required). To avoid creating too many sessions ThreadLocal class can be used as shown below to get the current session no matter how many times you make call to the currentSession() method.
public class HibernateUtil {
public static final ThreadLocal local = new ThreadLocal();
public static Session currentSession() throws HibernateException {
Session session = (Session) local.get();
//open a new session if this thread has no session if(session == null) {
session = sessionFactory.openSession(); local.set(session);
}
return session;
}
} It is also vital that you close your session after your unit of work completes.
Note: Keep your Hibernate Session API handy.

Which steps are involved in using hibernate for data acess operations?
Step1:create an initialize configuration object
configuration cfg=new configuration().configue();
Step2:Build a session factory
session factory sf=cfg.build session factory();
Step3:Create a session
session s=sf.open session
Step4:Start a transation
transation t=s.begin transaction();
Step5:use the various method of session to perform data access oprations like load(),save(),update(),remove().
Step6:Find the transation
t.commit();
t.rollback();
Step7:close the session
s.close();

What are the benefits of detached objects?
Answer: Detached objects can be passed across layers all the way up to the presentation layer without having to use any DTOs (Data Transfer Objects). You can later on re-attach the detached objects to another session.
What are the pros and cons of detached objects?
Pros: When long transactions are required due to user think-time, it is the best practice to break the long transaction up into two or more transactions.
You can use detached objects from the first transaction to carry data all the way up to the presentation layer.
These detached objects get modified outside a transaction and later on re-attached to a new transaction via another session.
Cons : In general, working with detached objects is quite cumbersome, and better to not clutter up the session with them if possible.
It is better to discard them and re-fetch them on subsequent requests.
This approach is not only more portable but also more efficient because - the objects hang around in Hibernate's cache anyway.
Also from pure rich domain driven design perspective it is recommended to use DTOs (DataTransferObjects) and DOs (DomainObjects) to maintain the separation between Service and UI tiers.

How does Hibernate distinguish between transient (i.e. newly instantiated) and detached objects?
Hibernate uses the “version” property, if there is one.
If not uses the identifier value. No identifier value means a new object. This does work only for Hibernate managed surrogate keys. Does not work for natural keys and assigned (i.e. not managed by Hibernate) surrogate keys.
Write your own strategy with Interceptor.isUnsaved().


What are requirement files in need to Hibernate?Give me one sample example?

Required Files
-------------
1) Persistent Class i.e Student.java
2) Hibernate Mapping File i.e student.hbm.xml
3) Hibernate Configuration File i.e hibernate.cfg.xml
4) Client Program to run i.e StudentClient.java

Persistant class means java bean class with private fields
and public set / get Methods and one default and parameterized
Constructor

Mapping file means to specify the bean fields with
database table fields

Configuration file means to specify the database information like
Driver class name, url,username,password etc..

Client Means to write the hibernate code instead of jdbc code

Student.java
-------------

package com.bhumana.hibernate;


public class Student
{
private String sname,email,phone;
private int sid;

Student(){}

public Student(String sname,String email,String phone)
{
this.sname=sname;
this.email=email;
this.phone=phone;
}

public void setSid(int sid)
{
this.sid=sid;
}

public void setSname(String sname)
{
this.sname=sname;
}
public void setEmail(String email)
{
this.email=email;
}
public void setPhone(String phone)
{
this.phone=phone;
}

public int getSid()
{
return sid;
}

public String getSname()
{
return sname;
}
public String getEmail()
{
return email;
}

public String getPhone()
{
return phone;
}
}

student.hbm.xml
----------------

hibernate.cfg.xml
-----------------

StudentClient.java
--------------------

package com.bhumana.hibernate;

import java.util.*;
import org.hibernate.*;
import org.hibernate.cfg.*;


public class StudentClient
{
public static void main(String args[])
{
try
{
Configuration cfg=new Configuration();
SessionFactory sf = cfg.configure().buildSessionFactory();
Session session = sf.openSession();
Transaction tx = session.beginTransaction();
Student stu = new Student("sudhakar","sud@bsr.com","90909");
session.save(stu);
tx.commit();
session.close();
} catch (Exception e)
{
e.printStackTrace();
}
}
}

What are the Core interfaces are of Hibernate framework?
The five core interfaces are used in just about every Hibernate application. Using these interfaces, you can store and retrieve persistent objects and control transactions.
1.Session interface
2.SessionFactory interface
3.Configuration interface
4.Transaction interface
5.Query and Criteria interfaces

What are the most common methods of Hibernate configuration?
The most common methods of Hibernate configuration are:
1.Programmatic configuration
2.XML configuration (hibernate.cfg.xml)

What Does Hibernate Simplify?
Hibernate simplifies:

  • Saving and retrieving your domain objects
  • Making database column and table name changes
  • Centralizing pre save and post retrieve logic
  • Complex joins for retrieving related items
  • Schema creation from object model

Why do you need ORM tools like hibernate?
The main advantage of ORM like hibernate is that it shields developers from messy SQL. Apart from this, ORM provides following benefits:
Improved productivity

  • High-level object-oriented API
  • Less Java code to write
  • No SQL to write

Improved performance

  • Sophisticated caching
  • Lazy loading
  • Eager loading

Improved maintainability

  • A lot less code to write
  • Improved portability
  • ORM framework generates database-specific SQL for you

What is ORM ?
ORM stands for object/relational mapping. ORM is the automated persistence of objects in a Java application to the tables in a relational database.

What is Hibernate Query Language (HQL)?
Hibernate offers a query language that embodies a very powerful and flexible mechanism to query, store, update, and retrieve objects from a database. This language, the Hibernate query Language (HQL), is an object-oriented extension to SQL.

What is the difference between and merge and update ?
Use update() if you are sure that the session does not contain an already persistent instance with the same identifier, and merge() if you want to merge your modifications at any time without consideration of the state of the session.

Define HibernateTemplate?
org.springframework.orm.hibernate.HibernateTemplate is a helper class which provides different methods for querying/retrieving data from the database. It also converts checked HibernateExceptions into unchecked DataAccessExceptions.

What are the benefits does HibernateTemplate provide?
The benefits of HibernateTemplate are :

  • HibernateTemplate, a Spring Template class simplifies interactions with Hibernate Session.
  • Common functions are simplified to single method calls.
  • Sessions are automatically closed.
  • Exceptions are automatically caught and converted to runtime exceptions.

What is component mapping in Hibernate?

  • A component is an object saved as a value, not as a reference
  • A component can be saved directly without needing to declare interfaces or identifier
  • properties Required to define an empty constructor
  • Shared references not supported

What is Hibernate proxy?

The proxy attribute enables lazy initialization of persistent instances of the class. Hibernate will initially return CGLIB proxies which implement the named interface.

The actual persistent object will be loaded when a method of the proxy is invoked.
Define cascade and inverse option in one-many mapping?
cascade - enable operations to cascade to child entities.cascade="allnonesave-updatedeleteall-delete-orphan"inverse - mark this collection as the "inverse" end of a bidirectional association.inverse="truefalse" Essentially "inverse" indicates which end of a relationship should be ignored, so when persisting a parent who has a collection of children, should you ask the parent for its list of children, or ask the children who the parents are?

What are the types of Hibernate instance states ?
Three types of instance states:
Transient -The instance is not associated with any persistence context
Persistent -The instance is associated with a persistence context
Detached -The instance was associated with a persistence context which has been closed – currently not associated

What are the differences between EJB 3.0 & Hibernate
Hibernate Vs EJB 3.0 :-
Hibernate :
Session–Cache or collection of loaded objects relating to a single unit of work

XDoclet Annotations used to support Attribute Oriented Programming

Defines HQL for expressing queries to the database

Supports Entity Relationships through mapping files and annotations in JavaDoc

EJB3.0:

Persistence Context-Set of entities that can be managed by a given EntityManager is defined by a persistence unit
Java 5.0 Annotations used to support Attribute Oriented Programming
Defines EJB QL for expressing queries
Support Entity Relationships through Java 5.0 annotations

What are the types of inheritance models in Hibernate?
There are three types of inheritance models in Hibernate:

  • Table per class hierarchy
  • Table per subclass
  • Table per concrete class

What is the advantage of Hibernate over jdbc?

  1. With JDBC, developer has to write code to map an object model's data representation to a relational data model and its corresponding database schema.
    Hibernate is flexible and powerful ORM solution to map Java classes to database tables. Hibernate itself takes care of this mapping using XML files so developer does not need to write code for this.
  2. With JDBC, the automatic mapping of Java objects with database tables and vice versa conversion is to be taken care of by the developer manually with lines of code.
    Hibernate provides transparent persistence and developer does not need to write code explicitly to map database tables tipples to application objects during interaction with RDBMS.
  3. JDBC supports only native Structured Query Language (SQL). Developer has to find out the efficient way to access database, i.e. to select effective query from a number of queries to perform same task.
  4. Hibernate provides a powerful query language Hibernate Query Language (independent from type of database) that is expressed in a familiar SQL like syntax and includes full support for polymorphic queries. Hibernate also supports native SQL statements. It also selects an effective way to perform a database manipulation task for an application.

What are the Collection types in Hibernate ?

  • Set
  • Bag
  • Array
  • List
  • Map

What are the ways to express joins in HQL?
HQL provides four ways of expressing (inner and outer) joins:-

  • An implicit association join
  • An ordinary join in the FROM clause
  • A fetch join in the FROM clause.
  • A theta-style join in the WHERE clause.

1 comment:

Anonymous said...

Hi

I read this post 2 times. It is very useful.

Pls try to keep posting.

Let me show other source that may be good for community.

Source: Sample interview questions

Best regards
Jonathan.