What is Hibernate?
Hibernate is a powerful, high performance object/relational persistence and query service.It is an open-source technology which fits well both with Java and .NET technologies.Hibernate lets developers write persistence classes with hibernate query features of HQL within principles of Object Oriented paradigm.It means one can include association,inheritance,polymorphism,composition and collection of these persisting objects to build applications.
Hibernate Architecture
The main objective of Hibernate is to relieve the developers from manual handling of SQLs,JDBC APIs for resultsets handling and it helps in keeping your data portable to various SQL databases,just by switching the delegate and driver details in hibernate.cfg.xml file.
Hibernate offers sophisticated query options, you can write plain SQL, object-oriented HQL (Hibernate Query Language), or create programmatic criteria and example queries. Hibernate can optimize object loading all the time, with various fetching and caching options.
Some snapshots of Hibernate:
-Free open source
-OO Concepts can be implemented.
-A rich variety of mappings for collections and dependent objects
-No extra code generation or bytecode processing steps in your build procedure
-Great performance, has a dual-layer cache architecture, and may be used in a cluster
-Its own query language support
-Efficient transaction handling
-The Java Persistence API is the standard object/relational mapping and persistence management interface of the Java EE 5.0 platform which are implemented with the Hibernate Annotations and Hibernate EntityManager modules, on top of the Hibernate Core.(As part of EJB3.0 spec)
Why Hibernate?
The reasons are plenty,weighing in favor of Hibernate clearly.
-Cost effective.Just imagine when you are using EJBs instead of Hibernate.One has to invest in Application Server(Websphere,Weblogic etc.),learning curve for EJB is slow and requires special training if your developers are not equipped with the EJB know-how.
-The developers get rid of writing complex SQLs and no more need of JDBC APIs for resultset handling.Even less code than JDBC.In fact the OO developers work well when they have to deal with object then writing lousy queries.
-High performance then EJBs(if we go by their industry reputation),which itself a container managed,heavyweight solution.
-Switching to other SQL database requires few changes in Hibernate configuration file and requires least clutter than EJBs.
-EJB itself has modeled itself on Hibernate principle in its latest version i.e. EJB3 because of apparent reasons.
What is ORM ?
Object Relational Mapping(ORM) is a technique/solution that provides an object-based view of data to applications which it can manipulate.The basic purpose of ORM is to allow an application written in an object oriented language to deal with the information it manipulates in terms of objects, rather than in terms of database-specific concepts such as rows, columns and tables.
In the Java world, ORM's first appearance was under the form of entity beans. But entity beans have limited scope in Java EE domain,they can not be exploited for Java SE based applications.The mapping of class lever attributes is done to table columns.For example a String variabe of a class will directly map onto a VARCHAR column. A relationship mapping is the one that you use when you have an attribute of a class that holds a reference to an instance of some other class in your domain model. The most common types of relationship mappings are "one to one", "one to many" or "many to many".
What are core interfaces for Hibernate framework?
Most Hibernate-related application code primarily interacts with four interfaces provided by Hibernate Core:
org.hibernate.Session
org.hibernate.SessionFactory
org.hibernate.Criteria
org.hibernate.Query
The Session is a persistence manager that manages operation like storing and retrieving objects. Instances of Session are inexpensive to create and destroy. They are not thread safe.
The application obtains Session instances from a SessionFactory. SessionFactory instances are not lightweight and typically one instance is created for the whole application. If the application accesses multiple databases, it needs one per database.
The Criteria provides a provision for conditional search over the resultset.One can retrieve entities by composing Criterion objects. The Session is a factory for Criteria.Criterion instances are usually obtained via the factory methods on Restrictions.
Query represents object oriented representation of a Hibernate query. A Query instance is obtained by calling Session.createQuery().
What is dirty checking in Hibernate?
Hibernate automatically detects object state changes in order to synchronize the updated state with the database, this is called dirty checking. An important note here is, Hibernate will compare objects by value, except for Collections, which are compared by identity. For this reason you should return exactly the same collection instance as Hibernate passed to the setter method to prevent unnecessary database updates.
What are different fetch strategies Hibernate have?
A fetching strategy in Hibernate is used for retrieving associated objects if the application needs to navigate the association. They may be declared in the O/R mapping metadata, or over-ridden by a particular HQL or Criteria query.
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.
Hibernate also distinguishes between:
Immediate fetching - an association, collection or attribute is fetched immediately, when the owner is loaded.
Lazy collection fetching - a collection is fetched when the application invokes an operation upon that collection. (This is the default for collections.)
"Extra-lazy" collection fetching - individual elements of the collection are accessed from the database as needed. Hibernate tries not to fetch the whole collection into memory unless absolutely needed (suitable for very large collections)
Proxy fetching - a single-valued association is fetched when a method other than the identifier getter is invoked upon the associated object.
"No-proxy" fetching - a single-valued association is fetched when the instance variable is accessed. Compared to proxy fetching, this approach is less lazy (the association is fetched even when only the identifier is accessed) but more transparent, since no proxy is visible to the application. This approach requires buildtime bytecode instrumentation and is rarely necessary.
Lazy attribute fetching - an attribute or single valued association is fetched when the instance variable is accessed. This approach requires buildtime bytecode instrumentation and is rarely necessary.
We use fetch to tune performance. We may use lazy to define a contract for what data is always available in any detached instance of a particular class.
[Source:Hibernate Reference Documentation]
Can you compare JDBC/DAO with Hibernate?
Hibernate and straight SQL through JDBC are different approaches.They both have their specific significance in different scenarios.If your application is not to big and complex,not too many tables and queries involved then it will be better to use JDBC. While Hibernate is a POJO based ORM tool,using JDBC underneath to connect to database, which lets one to get rid of writing SQLs and associated JDBC code to fetch resultset,meaning less LOC but more of configuration work.It will suit better when you have large application involving large volume of data and queries.Moreover lazy loading,caching of data helps in having better performance and you need not call the database every time rather data stays in object form which can be reused.
Explain different inheritance mapping models in Hibernate.
There can be three kinds of inheritance mapping in hibernate
1. Table per concrete class with unions
2. Table per class hierarchy
3. Table per subclass
Example:
We can take an example of three Java classes like Vehicle, which is an abstract class and two subclasses of Vehicle as Car and UtilityVan.
1. Table per concrete class with unions
In this scenario there will be 2 tables
Tables: Car, UtilityVan, here in this case all common attributes will be duplicated.
2. Table per class hierarchy
Single Table can be mapped to a class hierarchy
There will be only one table in database named 'Vehicle' which will represent all attributes required for all three classes.
Here it is be taken care of that discriminating columns to differentiate between Car and UtilityVan
3. Table per subclass
Simply there will be three tables representing Vehicle, Car and UtilityVan
Q. 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.
Q. 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();
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.
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 is the difference between the session.update() method and the session.lock() method?
Both of these methods and saveOrUpdate() method are intended for reattaching a detached object. The session.lock() method simply reattaches the object to the session without checking or updating the database on the assumption that the database in sync with the detached object. It is the best practice to use either session.update(..) or session.saveOrUpdate(). Use session.lock() only if you are absolutely sure that the detached object is in sync with your detached object or if it does not matter because you will be overwriting all the columns that would have changed later on within the same transaction.
Note: When you reattach detached objects you need to make sure that the dependent objects are reatched as well.
Q. How would you reatach detached objects to a session when the same object has already been loaded into the session?
You can use the session.merge() method call.
Q. What are the general considerations or best practices for defining your Hibernate persistent classes?
1.You must have a default no-argument constructor for your persistent classes and there should be getXXX() (i.e accessor/getter) and setXXX( i.e. mutator/setter) methods for all your persistable instance variables.
2.You should implement the equals() and hashCode() methods based on your business key and it is important not to use the id field in your equals() and hashCode() definition if the id field is a surrogate key (i.e. Hibernate managed identifier). This is because the Hibernate only generates and sets the field when saving the object.
3. It is recommended to implement the Serializable interface. This is potentially useful if you want to migrate around a multi-processor cluster.
4.The persistent class should not be final because if it is final then lazy loading cannot be used by creating proxy objects.
5.Use XDoclet tags for generating your *.hbm.xml files or Annotations (JDK 1.5 onwards), which are less verbose than *.hbm.xml files.

How can I count the number of query results without actually returning them?

Integer count = (Integer) session.createQuery("select count(*) from ....").uniqueResult();

How can I find the size of a collection without initializing it?

Integer size = (Integer) s.createFilter( collection, "select count(*)" ).uniqueResult();

How can I order by the size of a collection?

Use a left join, together with group by

select user
from User user
left join user.messages msg
group by user
order by count(msg)

How can I place a condition upon a collection size?

If your database supports subselects:

from User user where size(user.messages) >= 1