Thursday 10 February 2011

Hibernate Question Bank



Q. Why do you need ORM tools like hibernate?
Answer:
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
Q. What are the Core interfaces are of Hibernate framework?

Answer: 
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.
  • Session interface
  • SessionFactory interface
  • Configuration interface
  • Transaction interface
  • Query and Criteria interfaces

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

Answer: 

SessionFactory is Hibernates 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(); 


Q. 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. 
Session interface role:
  • Wraps a JDBC connection
  • Factory for Transaction
  • Holds a mandatory (first-level) cache of persistent objects, used when navigating the object graph or looking up objects by identifier

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

Q. What are the pros and cons of detached objects? 

Answer: 

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.
Q. How does Hibernate distinguish between transient (i.e. newly instantiated) and detached objects? 

Answer 

" 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(). 

Q. What is the difference between the session.get() method and the session.load() method? 

Both the session.get(..) and session.load() methods create a persistent object by loading the required object from the database. But if there was not such object in the database then the method session.load(..) throws an exception whereas session.get(&) returns null. 
Q. What’s the difference between load() and get()?
load() vs. get() :-
load() 
get() 
Only use the load() method if you are sure that the object exists. 
If you are not sure that the object exists, then use one of the get() methods. 
load() method will throw an exception if the unique id is not found in the database. 
get() method will return null if the unique id is not found in the database. 
load() just returns a proxy by default and database won’t be hit until the proxy is first invoked.  
get() will hit the database immediately. 

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

Q. How do you define sequence generated primary key in hibernate?
Using <generator> tag.
Example:-

<id column="USER_ID" name="id" type="java.lang.Long">
  
<generator class="sequence">
    
<param name="table">SEQUENCE_NAME</param>
 
 <generator>
</id>



Q. What do you mean by Named – SQL query?
Named SQL queries are defined in the mapping xml document and called wherever required.
Example:
<sql-query name = "empdetails">
  
<return alias="emp" class="com.test.Employee"/>
      SELECT emp.EMP_ID AS {emp.empid},
                 emp.EMP_ADDRESS AS {emp.address},
                 emp.EMP_NAME AS {emp.name}
      FROM Employee EMP WHERE emp.NAME LIKE :name

</sql-query>

Invoke Named Query :
List people = session.getNamedQuery("empdetails")
                      .setString(
"TomBrady", name)
                      .setMaxResults(50)
                      .list();

Q. How do you invoke Stored Procedures?

<sql-query name="selectAllEmployees_SP" callable="true">
 <return alias="emp" class="employee">
  
<return-property name="empid" column="EMP_ID"/>       

 
 <return-property name="name" column="EMP_NAME"/>     
 
 <return-property name="address" column="EMP_ADDRESS"/>
    {
? = call selectAllEmployees() }
 </return>
</sql-query>

Q. Explain Criteria API in Hibernate?
Criteria is a simplified API for retrieving entities by composing Criterion objects. This is a very convenient approach for functionality like "search" screens where there is a variable number of conditions to be placed upon the result set.
Example
 :
List employees = session.createCriteria(Employee.class)
                          .add(Restrictions.like(
"name", "a%") )
                          .add(Restrictions.like(
"address", "Boston"))
                           .addOrder(Order.asc(
"name") )
                           .list();

Q. Define HibernateTemplate?

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

Q. How do you switch between relational databases without code changes?
Using Hibernate SQL Dialects , we can switch databases. Hibernate will generate appropriate hql queries based on the dialect defined.

Q. 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
Q. How can a whole class be mapped as immutable?
Mark the class as mutable="false" (Default is true),. This specifies that instances of the class are (not) mutable. Immutable classes, may not be updated or deleted by the application.

Q. What is the use of dynamic-insert and dynamic-update attributes in a class mapping?
Criteria is a simplified API for retrieving entities by composing Criterion objects. This is a very convenient approach for functionality like "search" screens where there is a variable number of conditions to be placed upon the result set.
  • dynamic-update (defaults to false): Specifies that UPDATE SQL should be generated at runtime and contain only those columns whose values have changed
  • dynamic-insert (defaults to false): Specifies that INSERT SQL should be generated at runtime and contain only the columns whose values are not null.
Q. What do you mean by fetching strategy ?
A fetching strategy is the strategy Hibernate will use for retrieving associated objects if the application needs to navigate the association. Fetch strategies may be declared in the O/R mapping metadata, or over-ridden by a particular HQL or Criteria query.

Q. What are the Collection types in Hibernate ?
  • Bag
  • Set
  • List
  • Array
  • Map
Q. 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.
Q. What are the different fetching strategies in Hibernate?
Hibernate3 defines the following fetching strategies:
·         #Join fetching - Hibernate retrieves the associated instance or collection in the same SELECT, using an OUTER JOIN. #Select fetching - a second SELECT is used to retrieve the associated entity or collection. Unless you explicitly disable lazy fetching by specifying lazy="false", this second select will only be executed when you actually access the association.
·         #Subselect fetching - a second SELECT is used to retrieve the associated collections for all entities retrieved in a previous query or fetch. Unless you explicitly disable lazy fetching by specifying lazy="false", this second select will only be executed when you actually access the association.
·         #Batch fetching - an optimization strategy for select fetching - Hibernate retrieves a batch of entity instances or collections in a single SELECT, by specifying a list of primary keys or foreign keys.
Q. What is the difference between sorted and ordered collection in hibernate?
Answer.
 A sorted collection is sorted in-memory using java comparator, while order collection is ordered at the database level using order by clause.

Q. What is different cache available in hibernate?
Hibernate uses two different caches for objects: first-level cache and second-level cache. First- level cache is associated with the Session object, while second-level cache is associated with the Session Factory object.

Q. What is First-Level caching in hibernate?
Answer:
By default hibernate does first level caching using the persistent context (Session) with the help of dirty checking. It also cache the queries along with it’s calling parameters and result To use the query cache you must first enable it by setting the property hibernate.cache.use_query_cache to true in hibernate.properties
Hibernate uses this cache mainly to reduce the number of SQL queries it needs to generate within a given transaction. For example, if an object is modified several times within the same transaction, Hibernate will generate only one SQL UPDATE statement at the end of the transaction, containing all the modifications.

Q. What is Second-Level caching in hibernate?
Answer:
To reduce database traffic, second- level cache keeps loaded objects at the Session Factory level between transactions. These objects are available to the whole application, not just to the user running the query. This way, each time a query returns an object that is already loaded in the cache, one or more database transactions potentially are avoided. In addition, you can use a query-level cache if you need to cache actual query results, rather than just persistent objects. The query cache should always be used in conjunction with the second-level cache. Hibernate supports the following open-source cache implementations out-of-the-box:
·         EHCache: is a fast, lightweight, and easy-to-use in-process cache. It supports read-only and read/write caching, and memory- and disk-based caching. However, it does not support clustering.
·         OSCache: is another open-source caching solution. It is part of a larger package, which also provides caching functionalities for JSP pages or arbitrary objects. It is a powerful and flexible package, which, like EHCache, supports read-only and read/write caching, and memory- and disk-based caching. It also provides basic support for clustering via either JavaGroups or JMS.
·         SwarmCache: is a simple cluster-based caching solution based on JavaGroups. It supports read-only or nonstrict read/write caching (the next section explains this term). This type of cache is appropriate for applications that typically have many more read operations than write operations.
·         JBOSS TreeCache: is a powerful replicated (synchronous or asynchronous) and transactional cache. Use this solution if you really need a true transaction-capable caching architecture.
Q. How do you configure 2nd level cach in hibernate?
Answer:
To activate second-level caching, you need to define the hibernate.cache.provider_class property in the hibernate.cfg.xml file as follows:
<hibernate-configuration>
<session-factory>
<property name="hibernate.cache.provider_class">org.hibernate.cache.EHCacheProvider</property>
</session-factory>
</hibernate-configuration>

By default, the second-level cache is activated and uses the EHCache provider. To use the query cache you must first enable it by setting the property hibernate.cache.use_query_cache to true in hibernate.properties.