Saturday 1 August 2015

Hibernate interview question and answer

What is ORM?
ORM stands for Object-Relational Mapping (ORM) is a programming technique for converting data between relational databases and object oriented programming languages such as Java, C# etc.

Hibernate is an Object-Relational Mapping (ORM) solution for JAVA and rose as an open source persistent framework.  Hibernate maps Java classes to db tables and Java data types to SQL data types.



Hibernate Advantages:

·Hibernate takes care of mapping Java classes to database tables using XML files and without writing any line of code.
·Provides simple APIs for storing and retrieving Java objects directly to and from the database.
·If there is change in Database or in any table then the only need to change XML file properties.
·Hibernate does not require an application server to operate.
·Provides simple querying of data.

The Hibernate architecture
Hibernate uses various existing Java APIs, like JDBC, Java Transaction API (JTA), and Java Naming and Directory Interface (JNDI). JDBC allows almost any database with a JDBC driver to be supported by Hibernate. JNDI and JTA allow Hibernate to be integrated with J2EE application servers


Configuration Object:

The Configuration object is the first Hibernate object you create in any Hibernate application and usually created only once during application initialization. It represents a configuration or properties file required by the Hibernate. The Configuration object provides two keys components:
·Database Connection: This is handled through one or more configuration files supported by Hibernate. These files are hibernate.properties and hibernate.cfg.xml.

·Class Mapping Setup
This component creates the connection between the Java classes and database tables.

SessionFactory Object:

Configuration object creates a SessionFactory object which in turn configures Hibernate for the application using the supplied configuration file and allows for a Session object to be instantiated. The SessionFactory is a thread safe object and used by all the threads of an application.

The SessionFactory is heavyweight object so usually it is created during application start up and kept for later use. You would need one SessionFactory object per database using a separate configuration file. So if you are using multiple databases then you would have to create multiple SessionFactory objects.

Session Object:

A Session is used to get a physical connection with a database. The Session object is lightweight and designed to be instantiated each time an interaction is needed with the database. Persistent objects are saved and retrieved through a Session object.
The session objects should not be kept open for a long time because they are not usually thread safe and they should be created and destroyed as needed. The main function of the Session is to offer create, read and delete operations for instances of mapped entity classes. If the Session throws an exception, the transaction must be rolled back and the session must be discarded.

Persistent classes: Java classes whose objects or instances will be stored in database tables are called persistent classes in Hibernate.

Transaction Object: A Transaction represents a unit of work with the database and most of the RDBMS supports transaction functionality. This is an optional objectand Hibernate applications may choose not to use this interface, instead managing transactions in their own application code.

 

Query Object: Query objects use SQL or Hibernate Query Language (HQL) string to retrieve data from the database and create objects. A Query instance is used to bind query parameters, limit the number of results returned by the query, and finally to execute the query.

Criteria Object: Criteria object are used to create and execute object oriented criteria queries to retrieve objects.

 

Hibernate Configuration

Hibernate requires to know in advance where to find the mapping information that defines how your Java classes relate to the database tables. Hibernate also requires a set of configuration settings related to database and other related parameters. All such information is usually supplied as a standard Java properties file called hibernate.properties, or as an XML file named hibernate.cfg.xml.

Hibernate Properties:

 

S.N.
Properties and Description
1
hibernate.dialect
This property makes Hibernate generate the appropriate SQL for the chosen database.
2
hibernate.connection.driver_class
The JDBC driver class.
3
hibernate.connection.url
The JDBC URL to the database instance.
4
hibernate.connection.username
The database username.
5
hibernate.connection.password
The database password.
6
hibernate.connection.pool_size
Limits the number of connections waiting in the Hibernate database connection pool.
7
hibernate.connection.autocommit
Allows autocommit mode to be used for the JDBC connection.

hibernate.cfg.xml file
<hibernate-configuration>
    <session-factory>
   <property name="hibernate.dialect">
        org.hibernate.dialect.MySQLDialect
   </property>
   <property name="hibernate.connection.driver_class">
       com.mysql.jdbc.Driver
   </property>

   <!-- Assume test is the database name -->
   <property name="hibernate.connection.url">
      jdbc:mysql://localhost/test
   </property>
   <property name="hibernate.connection.username">
      root
   </property>
   <property name="hibernate.connection.password">
      root123
   </property>

   <!-- List of XML mapping files -->
   <mapping resource="Employee.hbm.xml"/>
   </session-factory>
</hibernate-configuration>

Employee.hbm.xml file

<hibernate-mapping>
   <class name="Employee" table="EMPLOYEE">
      <meta attribute="class-description">
         This class contains the employee detail.
      </meta>
      <id name="id" type="int" column="id">
         <generator class="native"/>
      </id>
      <property name="firstName" column="first_name" type="string"/>
      <property name="lastName" column="last_name" type="string"/>
      <property name="salary" column="salary" type="int"/>
   </class>
</hibernate-mapping>

The <generator> element within the id element is used to automatically generate the primary key values. classattribute of the generator element is set to native to let hibernate pick up either identity, sequence or hilo algorithm to create primary key depending upon the capabilities of the underlying database.
Association Mappings:
The mapping of associations between entity classes and the relationships between tables is the soul of ORM. Following are the four ways in which the relationship b/w the objects can be expressed.
Mapping type
Description
A many-to-one association is the most common kind of association where an Object can be associated with multiple objects. For example a same address object can be associated with multiple employee objects
<many-to-one name="address" column="address"  class="Address" not-null="true"/>
A one-to-one association is similar to many-to-one association with a difference that the column will be set as unique. For example an address object can be associated with a single employee object
<many-to-one name="address" column="address" unique="true"        class="Address" not-null="true"/>
A One-to-Many mapping can be implemented using a Set java collection that does not contain any duplicate element
<set name="certificates" cascade="all">
         <key column="employee_id"/>
         <one-to-many class="Certificate"/>
 </set>

Exp: Each Department can be associated with multiple Employees and each Employee can have only one Department.
A Many-to-Many mapping can be implemented using a Set java collection that does not contain any duplicate element
<set name="certificates" cascade="save-update" table="EMP_CERT">
         <key column="employee_id"/>
         <many-to-many column="certificate_id" class="Certificate"/>
 </set>

Exp: Each Employee can attain more than one meetings and each meetings can have more than one employee

Component Mappings:
It is very much possible that an Entity class can have a reference to another class as a member variable. If the referred class does not have its own life cycle and completely depends on the life cycle of the owning entity class, then the referred class is called as the Component class.

Hibernate Query Language
Hibernate Query Language (HQL) is an object-oriented query language, similar to SQL, but instead of operating on tables and columns, HQL works with persistent objects and their properties. HQL queries are translated by Hibernate into conventional SQL queries which in turns perform action on database.
Keywords like SELECT, FROM and WHERE etc. are not case sensitive but properties like table and column names are case sensitive in HQL
String hql = "SELECT E.firstName FROM Employee E";
Query query = session.createQuery(hql);
List results = query.list();

Hibernate Criteria Queries
The Hibernate Session interface provides createCriteria() method which can be used to create a Criteria object that returns instances of the persistence object's class when your application executes a criteria query. Following is the simplest example of a criteria query is one which will simply return every object that corresponds to the Employee class.

Criteria cr = session.createCriteria(Employee.class);
List results = cr.list();
Hibernate Caching
Caching is all about application performance optimization and it sits between your application and the database to avoid the number of database hits as many as possible to give a better performance.
First-level cache:
The first-level cache is the Session cache and is a mandatory cachethrough which all requests must pass. The Session object keeps an object under its own power before committing it to the database.
If you issue multiple updates to an object, Hibernate tries to delay doing the update as long as possible to reduce the number of update SQL statements issued. If you close the session, all the objects being cached are lost and either persisted or updated in the database.
Second-level cache:
Second level cache is an optional cache and first-level cache will always be consulted before any attempt is made to locate an object in the second-level cache. The second-level cache can be configured on a per-class and per-collection basis and mainly responsible for caching objects across sessions.
Any third-party cache can be used with Hibernate. An org.hibernate.cache.CacheProviderinterface is provided, which must be implemented to provide Hibernate with a handle to the cache implementation.
Query-level cache:
Hibernate also implements a cache for query result sets that integrates closely with the second-level cache. This is an optional feature and requires two additional physical cache regions that hold the cached query results and the timestamps when a table was last updated. This is only useful for queries that are run frequently with the same parameters. Every time the query is fired the cache manager checks for the combination of parameters and query. If the results are found in the cache they are returned otherwise a database transaction is initiated.
<property name="hibernate.cache.use_query_cache">true</property>

Hibernate Batch Processing
Consider a situation when you need to upload a large number of records into your database using Hibernate. Because by default, Hibernate will cache all the persisted objects in the session-level cache and ultimately your application would fall over with an OutOfMemoryException somewhere around the 50,000th row. You can resolve this problem if you are using batch processing with Hibernate.
To use the batch processing feature, first set hibernate.jdbc.batch_size as batch size to a number either at 20 or 50 depending on object size. This will tell the hibernate container that every X rows to be inserted as batch. To implement this in your code we would need to do little modification as follows:
Session session = SessionFactory.openSession();
Transaction tx = session.beginTransaction();
for ( int i=0; i<100000; i++ ) {
    Employee employee = new Employee(.....);
    session.save(employee);
                if( i % 50 == 0 ) { // Same as the JDBC batch size
        //flush a batch of inserts and release memory:
        session.flush();
        session.clear();
    }
}
tx.commit();
session.close();

Hibernate Interceptors
An object passes through different stages in its life cycle and Interceptor Interface provides methods which can be called at different stages to perform some required tasks. These methods are callbacks from the session to the application, allowing the application to inspect and/or manipulate properties of a persistent object before it is saved, updated, deleted or loaded.

What’s the difference between load() and 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. 

What is the difference between and merge and update?
If you have an attached object you can use update. If you have a detached object then use merge which first attaches the object to the session then will do an update. We can update the object in the session only.
Hibernate object states:
Transient- an object is transient if it has just been instantiated using the new operator, and it is not associated with a Hibernate Session. It has no persistent representation in the database and no identifier value has been assigned. Transient instances will be destroyed by the garbage collector if the application does not hold a reference anymore.

Persistent- a persistent instance has a representation in the database and an identifier value. It might just have been saved or loaded, however, it is by definition in the scope of a Session. Hibernate will detect any changes made to an object in persistent state and synchronize the state with the database when the unit of work completes.

Detached- a detached instance is an object that has been persistent, but its Session has been closed. The reference to the object is still valid, of course, and the detached instance might even be modified in this state. A detached instance can be reattached to a new Session at a later point in time, making it (and all the modifications) persistent again.

Difference in save/ update/ saveorUpdate

Hibernate has set of methods for saving and updating the values in the database. The methods which you are using are for updating its states and ultimately updated in database after the unit of work is completed. That happens when flush method is called.
·         Save: Save method stores an object into the database. That means it insert an entry if the identifier doesn’t exist, else it will throw error. If the primary key already present in the table, it cannot be inserted.
·         Update: Update method in hibernate is used for updating the object using identifier. If the identifier is missing or doesn’t exist, it will throw exception.
·         saveOrUpdate: This method calls save() or update() based on the operation. If the identifier exists, it will call update method else the save method will be called. saveOrUpdate() method does the following:
§  If the object is already persistent in the current session, it do nothing
§  If another object associated with the session has the same identifier, throw an exception to the caller
§  If the object has no identifier property, save() the object
§  If the object’s identifier has the value assigned to a newly instantiated object, save() the object
Define cascade and inverse option in one-many mapping?
Using cascade property we can ensure relationship with parent to child.
cascade="all|none|save-update|delete|all-delete-orphan"

inverse - mark this collection as the "inverse" end of a bidirectional association.
inverse="true|false"
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 is the difference between sorted and ordered collection in hibernate?
sorted collection 
order collection 
A sorted collection is sorting a collection by utilizing the sorting features provided by the Java collections framework.
Order collection is sorting a collection by specifying the order-by clause for sorting this collection when retrieval. 
If your collection is not large, it will be more efficient way to sort it. 
If your collection is very large, it will be more efficient way to sort it. 
What is the advantage of Hibernate over JDBC?
JDBC 
Hibernate 
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 itself takes care of this mapping using XML files so developer does not need to write code for this. 
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 tuples to application objects during interaction with RDBMS.  
JDBC supports only native Structured Query Language (SQL). Developer has to find out the efficient way to access database.
Hibernate provides HQL that is expressed in a familiar SQL like syntax. Hibernate also supports native SQL statements.  
As table changes or database is changed then it’s essential to change object structure as well as to change code written to map table-to-object/object-to-table. 
If there is change in Database or in any table then the only need to change XML file properties.  
In JDBC, mapping between Java objects and database tables is done manually.  
It relieves programmer from manual handling of persistent data, hence reducing the development time and maintenance cost.  
With JDBC, caching is maintained by hand-coding.  
Hibernate, with Transparent Persistence, cache is set to application work space. Relational tuples are moved to this cache as a result of query. Automatic Transparent Persistence allows the developer to concentrate more on business logic rather than this application code.  
In JDBC there is no check that always every user has updated data. This check has to be added by the developer.  
Hibernate enables developer to define version type field to application, due to this defined field Hibernate updates version field of database table every time relational tuple is updated in form of Java class object to that table.
What are the ways to express joins in HQL?
HQL provides four ways of expressing (inner and outer) joins:-
·         An implicitassociation join
·         An ordinary join in the FROM clause
·         A fetch join in the FROM clause.
·         A theta-stylejoin in the WHERE clause.
How can Hibernate be configured to access an instance variable directly and not through a setter method?  By mapping the property with access="field" in Hibernate metadata.
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.
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.

There are four fetching strategies
1. fetch-”join” = Disable the lazy loading, always load all the collections and entities.
2. fetch-”select” (default) = Lazy load all the collections and entities.
3. batch-size=”N” = Fetching up to ‘N’ collections or entities, *Not record*.
4. fetch-”subselect” = Group its collection into a sub select statement.
What is automatic dirty checking?
Automatic dirty checking is a feature that saves us the effort of explicitly asking Hibernate to update the database when we modify the state of an object inside a transaction.
What are Callback interfaces?
Callback interfaces allow the application to receive a notification when something interesting happens to an object—for example, when an object is loaded, saved, or deleted. Hibernate applications don't need to implement these callbacks, but they're useful for implementing certain kinds of generic functionality.
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 lazy loading and how do you achieve that in hibernate?
Lazy setting decides whether to load child objects while loading the Parent Object.
You need to specify parent class.Lazy = true in hibernate mapping file. By default the lazy loading of the child objects is true.
This make sure that the child objects are not loaded unless they are explicitly invoked in the application by calling getChild() method on parent. In this case hibernate issues a fresh database call to load the child when getChild() is actully called on the Parent object. But in some cases you do need to load the child objects when parent is loaded. Just make the lazy=false and hibernate will load the child when parent is loaded from the database. 
How do you configure 2nd level cache in hibernate?
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.

What are the ORM levels?
· Pure relational (stored procedure.)
· Light objects mapping (JDBC)
· Medium object mapping
·Full object Mapping (composition, inheritance, polymorphism, persistence by reachability)

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.

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>


No comments:

Post a Comment