HIBERNATE

1.what is Hibernate?

ans:

Hibernate is an ORM (Object Relational Mapping) Framework.

It just makes the DB connections/interactions much easier and reduces the dependency of the application towards a particular dbms, say MySQL/Oracle/DB2.

Basically has an XML which has the configuration of table to Model class mapping.

2.Why hibernate over JDBC?

ans:

1.JDBC is an api , that means it is partial, only interfaces and abstract classes are there, Hibernate provides concrete classes which provides the boiler plate logic.

2. in JDBC all the classes throws checked exception, there is no alternate path of execution but still we have to handle those exceptions.But in hibernate all the exceptions are unchecked exceptions.

3. In JDBC we have to manage the resource , like closing the connection, and other resource, but still there may be chance of memory leakage.But in hibernate the resource management is taken care by hibernate.

4. In JDBC the table name and column names are tightly coupled with your application, so any change in the database you have to modify the code, so it needs again development cost, as well as testing cost, which is waste of time, money and energy.But in jdbc The class name and columns are not tightly coupled with classes, those arte configured with mapping file(one xml), if any change in DB you can change in Mapping file.

5. Hibernate stores directly objects but jdbc can not.

6. Hibernate support versioning, that means if you modified one record (Object ) multiple times then it can be identified , how many times the object or record modified.

7. Hibernate supports lazy loading

8. Hibernate supports cacheing mechanism.

9. Hibernate supports Database independent queries. (HQL)

10. Hibernate supports generators.


3.what is the diff between save and persist?

ans:

Here is the difference between save and persist method:

First difference between save and persist is there return type. 

The return type of persist method is void while return type of save method is Serializable object. But both of them also INSERT records into database.

Another difference between persist and save is that both methods make a transient object to persistent state. However, persist() method doesn’t guarantee that the identifier value will be assigned to the persistent state immediately, the assignment might happen at flush time.

Third difference between save and persist method in Hibernate is behavior on outside of transaction boundaries. persist() method will not execute an insert query if it is called outside of transaction boundaries. Because save() method returns an identifier so that an insert query is executed immediately to get the identifier, no matter if it are inside or outside of a transaction.

Fourth difference between save and persist method in Hibernate: persist method is called outside of transaction boundaries, it is useful in long-running conversations with an extended Session context. On the other hand save method is not good in a long-running conversation with an extended Session context.


4.what are the important classes and interfaces in hibernate?

ans:

Below are the important classes and interfaces.

Configuration :-

    ->this is a class belongs to "org.hibernate.cfg" package.

->this class represents an entire set of mappings of an application's java types to an SQL database.

->we can create an instance for "SessionFactory" by using this "Configuration" object.

SessionFactory:-

->this is an interface belongs to "org.hibernate" package.

->this is used to create Session objects that manage connection data and mappings.

->we can obtain a session from SessionFactory object using "openSession()" method.


Session:-

->this is an interface belongs to "org.hibernate" package.

->this is used to create Transaction objects.

->we can use set of methods of Session interface for performing the database operations.


ex:-

save(),load(),get(),delete() etc.


Transaction :-

->this is an interface belongs to "org.hibernate" package.

->this is used for performing the transaction management.


ex:-

commit();


5.what are the steps required to perform database operations using hibernate?

ans:

->To use hibernate in an application to perform various persistent operations we need to implement some basic steps.

1.prepare Configuration object

2.build SessionFactory 

3.Obtain a Session

4.perform persistence operations

5.close the session


1.Prepare Configuration object :-

->the org.hibernate.cfg.Configuration object encapsulates the hibernate configuration details such as connection properties and dialect and mapping details described in the Hibernate mapping documents,which are used to build the SessionFactory.

->we can create a Hibernate Configuration object using its no-argument constructor.

syntax:-

Configuration cfg=new Configuration();

cfg.configure("hibernate.cfg.xml");

2.build SessionFactory :-

->after creating the Configuration object,then this object is used to create SessionFactory.to do this we use buildSessionFactory() method of Configuration.

syntax:-

Configuration cfg=new Configuration ();

cfg.configure();

SessionFactory sf=cfg.buildSessionFactory();


3.Obtain a Session:-

->The SessionFactory object is used to open a hibernate session.for this we need to use openSession() method of SessionFactory.

Configuration cfg=new Configuration();

cfg.configure();

SessionFactory sf=cfg.buildSessionFactory();

Session session=sf.openSession();


4.perform persistence operations :-

->the Session interface provides an abstraction for java application to perform the basic CRUD operations.

->for performing this we use the following methods.


->Object load(Class entityClass,Serializable id) :-

->locates the persistent instance of the given entity class with the given identifier.


->Serializable save(Object object):-

->the transient instance is persisted.

->void update(Object object):-

->Updates the persistent instance with the identifier of the given object.

->void saveOrUpdate(Object object):-

->Either save or update the given instance.


note:-

->all the above methods of Session interface allows the java application to use Hibernate for performing basic CRUD operations,but we have a requirement to query for persistent objects.to support this requirement Hibernate includes two interfaces.

1.Query

2.Criteria


5.close the session:-

->after we complete the use of Session,then we will close the session by using close() method.


Session session=sf.openSession();

session.close();


6.Is Hibernate Session a thread-safe object?

ans:

No, Session is not a thread-safe object, many threads can't access it simultaneously. In other words, you cannot share it between threads.


7.How to limit query results in HQL?

ans:

By using a method setMaxResults() of Query interface.

Query.setMaxResults()


8.what is the difference between sessionfactory and session?

ans:

SessionFactory is avialble for the whole appliacation .Session is only available for particular transaction.

SessionFactory provides second level cache and Session provides a first level cache.

SessionFactory is a thread safe and Session is not thread safe.  

There will be only one session factory object per hibenate client application.Because the implementation class of SessionFactory interface is singleton java class.


9.what is the difference between the save() and saveOrUpdate() methods in Hibernate?

ans:

Both the methods are used to store the objects into the database. Main difference is that save can only insert reords but saveOrUpdate can either insert or update records.


10.what is HQL?

ans:

HQL stands for Hibernate Query Language.It is a Object Oriented Language and independent of the database.

Hibernate includes get() and load() methods to retrieve the persistent objects .But here we can fetch only single record at a time.But in many sittiations if we want to fetch a more than one record and if we want to fetch only few properties of the object,then we use HQL.

HQL is like SQL,except that it uses objects instead of table names. 


11.explain about dirty cheking?

ans:

Dirty checking changes or updates only the fields that require action without touching the rest of the fields.

It helps developers avoid time consuming write actions.


12.what is lazy loading?

ans:

it is a technique in which objects are loaded as needed.it has been enabled by default since hibernate 3 to ensure that child objects are not loaded when the parent is.

13.what is the default cahce servie in Hibenate?

ans:

EhCache as the default cache provider.


14.how can we see hibernate generated sql on console?

ans:

We need to add following line in hibernate configuration file.

<property name="show_sql">true</property>


15.how primary key is created in hibenate?

ans:

if the table has one primary key,then in hbm file we need to onfigure this column by using <id> element.     

       <id name="empId" column="EMP_ID">

           <generator class="native"/>

       </id>


16.what is composite primary key?

ans: 

composite primary key means having more than one primary key.

if the table contains more than one primary key columns, then to configure these  primary columns, in hbm file new element called <composite-id> need to be used.

        <composite-id>

        <key-property name="id" column="eid"/>

        <key-property name="name" column="ename"/>

        </composite-id>


17.explain about named sql query and its benfits?

ans:

Hibernat names sql queries defines at central location and use them anywhere in the code.Named queries can be defined in two ways.

 1.by using hbm files:       

         <query name="findEmployeeByName">  

              <![CDATA[from Employee e where e.name = :name]]>  

         </query>

    2.by using annotation @NamedQuery


18.difference between get and load methods?

ans:

load mehod will throw an exception if an object with an ID passed to them is not found.

get mehod will return null if object not found.


19.difference between first level and second level cache?

ans:

First level cache is maintained at Session level while the second level cache is maintained at SessionFactory level and shared by all sessions.


20.Explain about hibernate life cycle?

ans:

   POJO class object having 3 states like…

Transient state

Persistent state

Detached state


Transient & Persistent states:

When ever an object of a pojo class is created then it will be in the Transient state.

When the object is in a Transient state it doesn’t represent any row of the database, it mean not associated with any Session object, if we speak more we can say no relation with the database its just an normal object If we modify the data of a pojo class object, when it is in transient state then it doesn’t effect on the database table When the object is in persistent state, then it represent one row of the database, if the object is in persistent state then it is associated with the unique Session if we want to move an object from persistent to detached state, we need to do either closing that session or need to clear the cache of the session if we want to move an object from persistent state into transient state then we need to delete that object permanently from the database.

example:-

import org.hibernate.*;

import org.hibernate.cfg.*;

public class ClientProgram { 

public static void main(String[] args)

{

Configuration cfg = new Configuration();

cfg.configure("hibernate.cfg.xml"); 

SessionFactory factory = cfg.buildSessionFactory();

Session session = factory.openSession();

               // Transient state_____start

Product p=new Product();

p.setProductId(101);

p.setProName("iPhone");

p.setPrice(25000);

         // Transient state_____end

         // Persistent state_____start

Transaction tx = session.beginTransaction();

session.save(p);

System.out.println("Object saved successfully.....!!");

tx.commit();

         // Persistent state_____end  

session.close();

factory.close();

}

}




Comments

Popular posts from this blog