Hibernate Interview Questions Part III

What is the advantage of Hibernate over JDBC?

There are so many,

  1. Hibernate is data base independent, your code will work for all ORACLE,MySQL ,SQLServer etc. In case of JDBC query must be data base specific.

  2. As Hibernate is set of Objects,you don't need to learn SQL language.You can treat TABLE as a Object.Only Java knowledge is need. In case of JDBC you need to learn SQL

  3. Don't need Query tuning in case of Hibernate.If you use Criteria Quires in Hibernate then hibernate automatically tuned your query and return best result with performance. In case of JDBC you need to tune your queries.

  4. You will get benefit of Cache. Hibernate support two level of cache.First level and 2nd level.So you can store your data into Cache for better performance. In case of JDBC you need to implement your java cache.

  5. Hibernate supports Query cache and It will provide the statistics about your query and database status. JDBC Not provides any statistics.

  6. Development fast in case of Hibernate because you don't need to write queries.

  7. No need to create any connection pool in case of Hibernate.You can use c3p0. In case of JDBC you need to write your own connection pool.

  8. In the xml file you can see all the relations between tables in case of Hibernate. Easy readability.

  9. You can load your objects on start up using lazy=false in case of Hibernate. JDBC don't have such support.

  10. Hibernate Supports automatic versioning of rows but JDBC Not.

Learn more about Hibernate in our Video Tutorial

Transaction with plain JDBC in Hibernate ?

If you don't have JTA and don't want to deploy it along with your application, you will usually have to fall back to JDBC transaction demarcation. Instead of calling the JDBC API you better use Hibernate's Transaction and the built-in session-per-request functionality.

To enable the thread-bound strategy in your Hibernate configuration:

set hibernate.transaction.factory_class to org.hibernate.transaction.JDBCTransactionFactory

set hibernate.current_session_context_class to thread

Difference between session.update() and session.lock() in Hibernate ?
  • 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.

  • Each interaction with the persistent store occurs in a new Session. However, the same persistent instances are reused for each interaction with the database. The application manipulates the state of detached instances originally loaded in another Session and then "reassociates" them using Session.update() or Session.saveOrUpdate().

You may also call lock() instead of update() and use LockMode.READ (performing a version check, bypassing all caches) if you are sure that the object has not been modified.

Difference between getCurrentSession() and openSession() in Hibernate ?
  • The "current session" refers to a Hibernate Session bound by Hibernate behind the scenes, to the transaction scope.

  • A Session is opened when getCurrentSession() is called for the first time and closed when the transaction ends.

  • It is also flushed automatically before the transaction commits. You can call getCurrentSession() as often and anywhere you want as long as the transaction runs.

  • To enable this strategy in your Hibernate configuration:

    Set hibernate.transaction.manager_lookup_class to a lookup strategy for your JEE container

    Set hibernate.transaction.factory_class to org.hibernate.transaction.JTATransactionFactory

  • Only the Session that you obtained with sf.getCurrentSession() is flushed and closed automatically.

Example :

  • If you decide to use manage the Session yourself the go for sf.openSession(), you have to flush() and close() it.

  • It does not flush and close() automatically.

Example :

How does Value replacement in Message Resource Bundle work?

In the resource bundle file, you can define a template like :

Then the Error message is : First Name is required.

Other constructors are :

    public ActionError(String key, Object value0, Object value1)
    . . .
    public ActionError(String key, Object[] values);

How to add .hbm.xml file in sessionFactory?
How to get JDBC connections in hibernate?

User Session.connection() method to get JDBC Connection.

How to create Session and SessionFactory in Hibernate?

Step 1. Put Hibernate properties in the classpath.

Step 2. Put .hbm.xml in class path.

Code is Here to create session ...

What are the Instance states in Hibernate?
  • transient :
    The instance is not, and has never been associated with any persistence context. It has no persistent identity (primary key value).

  • persistent :
    The instance is currently associated with a persistence context. It has a persistent identity (primary key value) and, perhaps, a corresponding row in the database. For a particular persistence context, Hibernate guarantees that persistent identity is equivalent to Java identity (in-memory location of the object).

  • detached :
    The instance was once associated with a persistence context, but that context was closed, or the instance was serialized to another process. It has a persistent identity and, perhaps, a corresponding row in the database.
    For detached instances, Hibernate makes no guarantees about the relationship between persistent identity and Java identity.

What are the core components in Hibernate ?
  • SessionFactory (org.hibernate.SessionFactory) :
    A threadsafe (immutable) cache of compiled mappings for a single database. A factory for Session and a client of ConnectionProvider. Might hold an optional (second-level) cache of data that is reusable between transactions, at a process- or cluster-level.

  • Session (org.hibernate.Session) :

    • A single-threaded, short-lived object representing a conversation between the application and the persistent store. 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.

    • Persistent objects and collections Short-lived, single threaded objects containing persistent state and business function. These might be ordinary JavaBeans/POJOs, the only special thing about them is that they are currently associated with (exactly one) Session. As soon as the Session is closed, they will be detached and free to use in any application layer (e.g. directly as data transfer objects to and from presentation).

    • Transient and detached objects and collections Instances of persistent classes that are not currently associated with a Session. They may have been instantiated by the application and not (yet) persisted or they may have been instantiated by a closed Session.

  • Transaction (org.hibernate.Transaction) :
    (Optional) A single-threaded, short-lived object used by the application to specify atomic units of work. Abstracts application from underlying JDBC, JTA or CORBA transaction. A Session might span several Transactions in some cases. However, transaction demarcation, either using the underlying API or Transaction, is never optional!

  • Architecture Hibernate 3.0.2 9

  • ConnectionProvider (org.hibernate.connection.ConnectionProvider) :
    (Optional) A factory for (and pool of) JDBC connections. Abstracts application from underlying Datasource or DriverManager. Not exposed to application, but can be extended/implemented by the developer.

  • TransactionFactory (org.hibernate.TransactionFactory) :
    (Optional) A factory for Transaction instances. Not exposed to the application, but can be extended/ implemented by the developer.

  • Extension Interfaces :
    Hibernate offers many optional extension interfaces you can implement to customize the behavior of your persistence layer. See the API documentation for details.