Only Institute
to provide recording daily after class to students. you can practice whole day under faculty guidance. where test and mockup tests are taken regularly. provides all mobile nos of old students on website.

Hibernate Interview Question Answer Part 3

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.
session.save() :

Save does an insert and will fail if the primary key is already persistent.

session.saveOrUpdate() : saveOrUpdate does a select first to determine if it needs to do an insert or an update. Insert data if primary key not exist otherwise update data.

session.persist() : Does the same like session.save().
But
session.save() return Serializable object but session.persist() return void.
session.save() returns the generated identifier (Serializable object) and session.persist() doesn't.

For Example :
if you do :-

System.out.println(session.save(question));
This will print the generated primary key.

if you do :-

System.out.println(session.persist(question));
Compile time error because session.persist() return void.
SLazy fetching decides whether to load child objects while loading the Parent Object.
You need to do this setting respective hibernate mapping file of the parent class.
Lazy = true (means not to load child)
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

Example :
If you have a TABLE ? EMPLOYEE mapped to Employee object and contains set of Address objects.
Parent Class : Employee class
Child class : Address Class


public class Employee { 
private Set address = new HashSet(); // contains set of child Address objects 
public Set getAddress () { 
return address; 
} 
public void setAddresss(Set address) { 
this. address = address; 
} 
} 


In the Employee.hbm.xml file

In the above configuration.
If lazy="false" : - when you load the Employee object that time child object Adress is also loaded and set to setAddresss() method. If you call employee.getAdress() then loaded data returns.No fresh database call.

If lazy="true" :- This the default configuration. If you don?t mention then hibernate consider lazy=true. when you load the Employee object that time child object Adress is not loaded. You need extra call to data base to get address objects. If you call employee.getAdress() then that time database query fires and return results. Fresh database call.
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.
Step 1.
In the struts-config.xml add plugin

Step 2. In the applicationContext.xml file
Configure datasourse

oracle.jdbc.driver.OracleDriver
jdbc:oracle:thin:@10.10.01.24:1541:ebizd

Step 3.
Configure SessionFactory
com/test/dbxml/User.hbm.xml
net.sf.hibernate.dialect.OracleDialect

Step 4.
Configure User.hbm.xml

Step 5.
In the applicationContext.xml ? configure for DAO

Step 6.


DAO Class 
public class UserDAOHibernate extends HibernateDaoSupport implements UserDAO { 
private static Log log = LogFactory.getLog(UserDAOHibernate.class); 

public List getUsers() { 
return getHibernateTemplate().find("from User"); 
} 

public User getUser(Long id) { 
return (User) getHibernateTemplate().get(User.class, id); 
} 

public void saveUser(User user) { 
getHibernateTemplate().saveOrUpdate(user); 

if (log.isDebugEnabled()) { 
log.debug("userId set to: " + user.getId()); 
} 
} 

public void removeUser(Long id) { 
Object user = getHibernateTemplate().load(User.class, id); 
getHibernateTemplate().delete(user); 
} 
} 


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





Session session = factory.openSession(); 
Transaction tx = null; 
try { 
tx = session.beginTransaction(); 
// Do some work 
session.load(...); 
session.persist(...); 
tx.commit(); // Flush happens automatically 
} 
catch (RuntimeException e) { 
tx.rollback(); 
throw e; // or display error message 
} 
finally { 
session.close(); 
}




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().


// foo is an instance loaded by a previous Session 
foo.setProperty("bar"); 
session = factory.openSession(); 
session.saveOrUpdate(foo); 
session.flush(); 
session.connection().commit(); 
session.close(); 


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.
getCurrentSession() :
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.



try { 
UserTransaction tx = (UserTransaction)new InitialContext() 
.lookup("java:comp/UserTransaction"); 

tx.begin(); 

// Do some work 
sf.getCurrentSession().createQuery(...); 
sf.getCurrentSession().persist(...); 

tx.commit(); 
} 
catch (RuntimeException e) { 
tx.rollback(); 
throw e; // or display error message 
} 

openSession() : 
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 : 
UserTransaction tx = (UserTransaction)new InitialContext() 
.lookup("java:comp/UserTransaction"); 

Session session = factory.openSession(); 

try { 
tx.begin(); 

// Do some work 
session.createQuery(...); 
session.persist(...); 

session.flush(); // Extra work you need to do 

tx.commit(); 
} 
catch (RuntimeException e) { 
tx.rollback(); 
throw e; // or display error message 
} 
finally { 
session.close(); // Extra work you need to do 
}


saveOrUpdate() does the following:
? if the object is already persistent in this session, do nothing
? if another object associated with the session has the same identifier, throw an exception
? if the object has no identifier property, save() it
? if the object's identifier has the value assigned to a newly instantiated object, save() it
? if the object is versioned (by a or ), and the version property value is the same
value assigned to a newly instantiated object, save() it
? otherwise update() the object
merge() is very different:
? if there is a persistent instance with the same identifier currently associated with the session, copy the state
of the given object onto the persistent instance
? if there is no persistent instance currently associated with the session, try to load it from the database, or
create a new persistent instance
? the persistent instance is returned
? the given instance does not become associated with the session, it remains detached
In the resource bundle file, you can define a template like:
errors.required={0} is required.
ActionErrors errors = new ActionErrors();
errors.add(ActionErrors.GLOBAL_ERROR,
new ActionError("error.custform","First Name"));
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);
In the resource bundle file, you can define a template like:


errors.required={0} is required.
ActionErrors errors = new ActionErrors();
errors.add(ActionErrors.GLOBAL_ERROR,
new ActionError("error.custform","First Name"));


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);



SessionFactory sf = new Configuration() 
.addFile("Item.hbm.xml") 
.addFile("Bid.hbm.xml") 
.buildSessionFactory();


User Session.connection() method to get JDBC Connection.
Step 1> Put Hibernate properties in the classpath.

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

Code is Here to create session ...


package com.dao; 
import java.io.File; 
import java.io.FileInputStream; 
import java.util.Properties; 
import org.apache.log4j.Logger; 
import org.hibernate.HibernateException; 
import org.hibernate.Session; 
import org.hibernate.SessionFactory; 
import org.hibernate.Transaction; 
import org.hibernate.cfg.Configuration; 

/** 
* 
* @author Satya Das 
*/ 
public class HibernateUtil { 
    protected static final Logger logger=Logger.getLogger(HibernateUtil.class); 
    public static String appHome = "No"; 
     
     
    private static SessionFactory sessionFactory; 
     
     
    private static final ThreadLocal threadSession = new ThreadLocal(); 
    private static final ThreadLocal threadTransaction = new ThreadLocal(); 
     
     
     
    /** 
     * Initialize Hibernate Configuration 
     */ 
    public static void initMonitor(){ 
        logger.info("Hibernate configure"); 
        try { 
            logger.info("appHome"+appHome); 
            String path_properties = appHome+File.separatorChar+"hibernate.properties"; 
            String path_mapping = appHome+File.separatorChar+"mapping_classes.mysql.hbm.xml"; 
            //String ecache = appHome+File.separatorChar+"ehcache.xml"; 
             
             
            Properties propHibernate = new Properties(); 
            propHibernate.load(new FileInputStream(path_properties)); 
             
            Configuration configuration = new Configuration(); 
            configuration.addFile(path_mapping); 
            configuration.setProperties(propHibernate); 
             
            /* try { 
CacheManager.create(ecache); 
} catch (CacheException e) { 
// logger.logError(e); 
}*/ 
             
            sessionFactory = configuration.buildSessionFactory(); 
             
             
             
        } catch (Throwable ex) { 
            logger.error("Exception in initMonitor",ex); 
            throw new ExceptionInInitializerError(ex); 
        } 
    } 
    /** 
     * @return a Session Factory Object 
     */ 
    public static SessionFactory getSessionFactory() { 
        logger.info("Inside getSessionFactory method"); 
        try { 
             
            if (sessionFactory == null) { 
                initMonitor(); 
            }else { 
                 
                //sessionFactory.getStatistics().logSummary(); 
            } 
             
             
        } catch (Exception e) { 
            logger.error("Exception in getSessionFactory",e); 
        } 
         
        return sessionFactory; 
    } 
     
    /** 
     * @return Session . Start a Session 
     */ 
    public static Session getSession() { 
         
        Session s = (Session) threadSession.get(); 
        logger.debug("session"+s); 
        if (s == null) { 
             
            s = getSessionFactory().openSession(); 
            threadSession.set(s); 
            logger.debug("session 1 $"+s); 
        } 
        return s; 
    } 
     
    /** 
     * Close Session 
     */ 
    public static void closeSession(){ 
         
        Session s = (Session) threadSession.get(); 
        threadSession.set(null); 
        if (s != null && s.isOpen()) { 
            s.flush(); 
            s.close(); 
        } 
    } 
     
     
    /** 
     * Start a new database transaction. 
     */ 
    public static void beginTransaction(){ 
        Transaction tx = null; 
         
        if (tx == null) { 
            tx = getSession().beginTransaction(); 
            threadTransaction.set(tx); 
        } 
    } 
     
    /** 
     * Commit the database transaction. 
     */ 
    public static void commitTransaction(){ 
        Transaction tx = (Transaction) threadTransaction.get(); 
        try { 
            if ( tx != null ) { 
                tx.commit(); 
            } 
             
            threadTransaction.set(null); 
             
        } catch (HibernateException ex) { 
            rollbackTransaction(); 
             
            throw ex; 
        } 
    } 
     
     
    /** 
     * Rollback the database transaction. 
     */ 
    public static void rollbackTransaction(){ 
         
        Transaction tx = (Transaction) threadTransaction.get(); 
        try { 
            threadTransaction.set(null); 
            if ( tx != null && !tx.wasCommitted() && !tx.wasRolledBack() ) { 
                tx.rollback(); 
            } 
        } finally { 
            closeSession(); 
        } 
    } 
          
} 



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 corrsponding row in the database. For detached instances, Hibernate makes no guarantees about the relationship between persistent identity and Java identity.
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.