Clouds
Home

Test Driven Development

Aspect Oriented Programming

Annotation Based Programming

Inversion Of Control - Part 1

Inversion Of Control - Part 2

Hibernate Interview Questions - Part 1

Hibernate Interview Questions - Part 2

Hibernate Interview Questions - Part 3

Spring Interview Questions

EJB 3.0 Interview Questions

Hibernate Interview Questions - Part 1


Explain Object-to-Relational (O/R) mapping ?

There are several ways to persist data and the persistence layer is one of the most important layers in any application development. O/R mapping is a technique of mapping data representation from an object model to a SQL based relational model. O/R mapping is well suited for read -> modify -> write centric applications and not suited for write centric applications (i.e. batch processes with large data sets like 5000 rows or more) where data is seldom read. Although this was generally true of many earlier O/R mapping frameworks, most today (including latest Hibernate) allow for efficient ways of performing large batch style write operations. O/R mapping tools/frameworks allow you to model inheritance, association and composition class relationships. O/R mapping tools work well in 80-90% of cases. Use basic database features like stored procedures, triggers etc, when O/R mapping is not appropriate. Keep in mind that no one size fits all solution. Always validate your architectural design with a vertical slice and test for performance. Some times you have to handcraft your SQL and a good O/R mapping (aka ORM) tool/framework should allow that. O/R mapping tools/frameworks allow your application to be:
  • Less verbose (e.g. transparent persistence , Object Oriented query language , transitive persistence etc)
  • More portable (i.e. vendor independence due to multi dialect support )
  • More maintainable (i.e. transparent persistence, inheritance mapping strategies, automatic dirty checking etc).
  • Takes care of much of the plumbing like connection establishment, exception handling, configuration etc. You can often leverage the framework’s strategies and capabilities to get efficiencies. Also provides support for eager fetching, lazy loading (i.e. using proxy objects), caching strategies and detached objects (no DTOs required). Hibernate is a popular O/R mapping (aka ORM) framework, which provides above mentioned benefits and features.

    Give an overview of hibernate framework ?

    Hibernate is a full-featured, open source Object-to-Relational (O/R) mapping framework. Unlike EJB (EJB’s new persistence API can operate outside of an EJB container), Hibernate can work inside or outside of a J2EE container. Hibernate works with Plain Old Java Objects (POJOs), which is much like a JavaBean.

    How will you configure Hibernate ?

    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 service (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 numbers 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 ?

    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 threads ?

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

    Explain hibernate object states ? Explain hibernate objects lifecycle ?

    Persistent

    Persistent objects and collections are short lived single threaded objects, which store the persistent state. These objects synchronize their state with the database depending on your flush strategy (i.e. auto-flush where as soon as setXXX() method is called or an item is removed from a Set, List etc or define your own synchronization points with session.flush(), transaction.commit() calls). If you remove an item from a persistent collection like a Set, it will be removed from the database either immediately or when flush() or commit() is called depending on your flush strategy. They are Plain Old Java Objects (POJOs) and are currently associated with a session. As soon as the associated session is closed, persistent objects become detached objects and are free to use directly as data transfer objects in any application layers like business layer, presentation layer etc.

    Detached

    Detached objects and collections are instances of persistent objects that were associated with a session but currently not associated with a session. These objects can be freely used as Data Transfer Objects without having any impact on your database. Detached objects can be later on attached to another session by calling methods like session.update(), session.saveOrUpdate() etc. and become persistent objects.

    Transient

    Transient objects and collections are instances of persistent objects that were never associated with a session. These objects can be freely used as Data Transfer Objects without having any impact on your database. Transient objects become persistent objects when associated to a session by calling methods like session.save(), session.persist() etc.

    What are the benefits of detached objects ?

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

    Session session1 = sessionFactory.openSession();
    Car myCar = session1.get(Car.class, carId); //"myCar" is a persistent object at this stage.
    session1.close(); //once the session is closed "myCar" becomes a detached object


    you can now pass the "myCar" object all the way upto the presentation tier. It can be modified without any effect to your database table.

    myCar.setColor("Red"); //no effect on the database

    When you are ready to persist this change to the database, it can be reattached to another session as shown below:

    Session session2 = sessionFactory.openSession(); Transaction tx = session2.beginTransaction(); session2.update(myCar); //detached object "myCar" gets re-attached tx.commit(); //change is synchronized with the database. session2.close()

  • 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 reattached to a new transaction via another session.
  • 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 is a Hibernate transaction object ?

    Transaction is a single threaded, short lived object used by the application to specify atomicity. Transaction abstracts your application code from underlying JDBC, JTA or CORBA transactions. At times a session can span several transactions. 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.

    Transaction tx = session.beginTransaction();
    Employee emp = new Employee();
    emp.setName("Brian");
    emp.setSalary(1000.00);
    session.save(emp);
    tx.commit();
    //close session


    How do you query the database with Hibernate ?

    Hibernate provides a very robust querying API that supports query strings, named queries and queries built as aggregate expressions. The most flexible way is using the Hibernate Query Language syntax (HQL), which is easy to understand and is an Object Oriented extension to SQL, which supports inheritance and polymorphism.

    Query query = session.createQuery("Select car from Car as car where car.color = :color");
    query.setString("color","black");
    List list = query.list();


    HQL

  • HQL uses classes and properties instead of tables and columns.
  • HQL is less verbose than SQL and supports automatic association joining.
  • Select car from Car as car join car.parts as part where car.color = ‘black’ and part.cost>100");

    SQL

  • SQL uses tables and columns and is more verbose.
  • Select car.* from Car as car join Part part on car.part_id = part.id where car.color = ‘black’ and part.cost > 100"); Type-safe queries can be handled by the object oriented query by criteria approach.

    String color = "black";
    Criteria criteria = session.createCriteria(Car.class);
    criteria.add(Expression.eq("color", color));
    Collection col = criteria.list();


    You can also use Hibernate’s direct SQL query feature. If none of the above meets your requirements then you can get a plain JDBC connection from a Hibernate session.

    Hibernate Interview Questions - Part 2 >>>




    Home Clouds