Thursday, August 8, 2013

Hibernate interview Questions



11.      Difference between session.load() and session.get() ?
load() will throw an unrecoverable exception if there is no matching database row.  
get() will return null if there is no matching database row.
Cat fritz = (Cat) session.load(Cat.class, "1");
Return the Cat Object with key 1. If there is no Cat Object with key 1 then throw will throw an unrecoverable exception.
If the class is  mapped with a proxy, load() just returns an uninitialized proxy and does not actually hit the database until you invoke a method of the proxy. This behaviour is very useful if you wish to create an association to an object
without actually loading it from the database. It also allows multiple instances to be loaded as a batch if batchsize is defined for the class mapping.
Cat fritz = (Cat) session.get(Cat.class, "1");
If you are not certain that a matching row exists, you should use the get() method, which hits the database immediately
and returns null if there is no matching row.

2.      Difference between session.save() , session.saveOrUpdate() and session.persist()?

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.
 

3.What is the difference between hibernate and 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.

4. What is lazy fetching in Hibernate? With Example

Lazy 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.
What is the Lazy Loading and eagerly loading?
Lazy loading :: based on requirement
Eagerly loading :: load all the data at  one time.

5. 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.
6. How to Integrate Struts Spring Hibernate ?
Details with code you can deploy in tomcat server and test .
http://www.techfaq360.com/tutorial/spring/struts_spring_hibernate.jsp
Step 1.
In the struts-config.xml add plugin

value="/WEB-INF/applicationContext.xml"/>


Step 2.
In the applicationContext.xml file
Configure datasourse

oracle.jdbc.driver.OracleDriver

jdbc:oracle:thin:@10.10.01.24:1541:ebizd

sa
    


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

7.How to prevent concurrent update in Hibernate?

version checking used in hibernate when more then one thread trying to access same data.
For example :
User A edit the row of the TABLE for update ( In the User Interface changing data - This is user thinking time)
and in the same time User B edit the same record for update and click the update.
Then User A click the Update and update done. Chnage made by user B is gone.
In hibernate you can perevent slate object updatation using version checking.
Check the version of the row when you are upding the row.
Get the version of the row when you are fetching the row of the TABLE for update.
On the time of updation just fetch the version number and match with your version number ( on the time of fetching).
This way you can prevent slate object updatation.

Steps 1:
Declare a variable "versionId" in your Class with setter and getter.
public class Campign {
private Long versionId;
private Long campignId;
private String name;
public Long getVersionId() {
return versionId;
}
public void setVersionId(Long versionId) {
this.versionId = versionId;
}

public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}

public Long getCampignId() {
        return campignId;
    }
private void setCampignId(Long campignId) {
        this.campignId = campignId;
    }

}

Step 2.
In the .hbm.xml file




CAMPIGN_ID_SEQ


    

    





Step 3.
Create a coulmn name "version" in the CAMPIGN table.

Step 4.
In the code
// foo is an instance loaded by a previous Session
session = sf.openSession();
int oldVersion = foo.getVersion();
session.load( foo, foo.getKey() );
if ( oldVersion!=foo.getVersion ) throw new StaleObjectStateException();
foo.setProperty("bar");
session.flush();
session.connection().commit();
session.close();


You can handle StaleObjectStateException() and do what ever you want.
You can display error message.

Hibernate autumatically create/update the version number when you update/insert any row in the table.

8.How to perevent slate object updatation in Hibernate ?

version checking used in hibernate when more then one thread trying to access same data.
For example :
User A edit the row of the TABLE for update ( In the User Interface changing data - This is user thinking time)
and in the same time User B edit the same record for update and click the update.
Then User A click the Update and update done. Chnage made by user B is gone.
In hibernate you can perevent slate object updatation using version checking.
Check the version of the row when you are upding the row.
Get the version of the row when you are fetching the row of the TABLE for update.
On the time of updation just fetch the version number and match with your version number ( on the time of fetching).
This way you can prevent slate object updatation.
Steps 1:
Declare a variable "versionId" in your Class with setter and getter.
public class Campign {
private Long versionId;
private Long campignId;
private String name;
public Long getVersionId() {
return versionId;
}
public void setVersionId(Long versionId) {
this.versionId = versionId;
}

public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}

public Long getCampignId() {
        return campignId;
    }
private void setCampignId(Long campignId) {
        this.campignId = campignId;
    }

}

Step 2.
In the .hbm.xml file




CAMPIGN_ID_SEQ


    

    





Step 3.
Create a coulmn name "version" in the CAMPIGN table.

Step 4.
In the code
// foo is an instance loaded by a previous Session
session = sf.openSession();
int oldVersion = foo.getVersion();
session.load( foo, foo.getKey() );
if ( oldVersion!=foo.getVersion ) throw new StaleObjectStateException();
foo.setProperty("bar");
session.flush();
session.connection().commit();
session.close();


You can handle StaleObjectStateException() and do what ever you want.
You can display error message.

Hibernate autumatically create/update the version number when you update/insert any row in the table

9. What is version checking in Hibernate ?

version checking used in hibernate when more then one thread trying to access same data.
For example :
User A edit the row of the TABLE for update ( In the User Interface changing data - This is user thinking time)
and in the same time User B edit the same record for update and click the update.
Then User A click the Update and update done. Chnage made by user B is gone.

In hibernate you can perevent slate object updatation using version checking.

Check the version of the row when you are upding the row.
Get the version of the row when you are fetching the row of the TABLE for update.
On the time of updation just fetch the version number and match with your version number ( on the time of fetching).
This way you can prevent slate object updatation.
Steps 1:
Declare a variable "versionId" in your Class with setter and getter.
public class Campign {
private Long versionId;
private Long campignId;
private String name;
public Long getVersionId() {
return versionId;
}
public void setVersionId(Long versionId) {
this.versionId = versionId;
}

public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}

public Long getCampignId() {
        return campignId;
    }
private void setCampignId(Long campignId) {
        this.campignId = campignId;
    }

}

Step 2.
In the .hbm.xml file




CAMPIGN_ID_SEQ


    

    





Step 3.
Create a coulmn name "version" in the CAMPIGN table.

Step 4.
In the code
// foo is an instance loaded by a previous Session
session = sf.openSession();
int oldVersion = foo.getVersion();
session.load( foo, foo.getKey() );
if ( oldVersion!=foo.getVersion ) throw new StaleObjectStateException();
foo.setProperty("bar");
session.flush();
session.connection().commit();
session.close();


You can handle StaleObjectStateException() and do what ever you want.
You can display error message.

Hibernate autumatically create/update the version number when you update/insert any row in the table.

10 .How to handle user think time using hibernate ?

version checking used in hibernate when more then one thread trying to access same data.
For example :
User A edit the row of the TABLE for update ( In the User Interface changing data - This is user thinking time)
and in the same time User B edit the same record for update and click the update.
Then User A click the Update and update done. Chnage made by user B is gone.

In hibernate you can perevent slate object updatation using version checking.

Check the version of the row when you are upding the row.
Get the version of the row when you are fetching the row of the TABLE for update.
On the time of updation just fetch the version number and match with your version number ( on the time of fetching).

This way you can prevent slate object updatation.

Steps 1:
Declare a variable "versionId" in your Class with setter and getter.
public class Campign {
private Long versionId;
private Long campignId;
private String name;
public Long getVersionId() {
return versionId;
}
public void setVersionId(Long versionId) {
this.versionId = versionId;
}

public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}

public Long getCampignId() {
        return campignId;
    }
private void setCampignId(Long campignId) {
        this.campignId = campignId;
    }

}

Step 2.
In the .hbm.xml file




CAMPIGN_ID_SEQ


    

    





Step 3.
Create a coulmn name "version" in the CAMPIGN table.

Step 4.
In the code
// foo is an instance loaded by a previous Session
session = sf.openSession();
int oldVersion = foo.getVersion();
session.load( foo, foo.getKey() );
if ( oldVersion!=foo.getVersion ) throw new StaleObjectStateException();
foo.setProperty("bar");
session.flush();
session.connection().commit();
session.close();


You can handle StaleObjectStateException() and do what ever you want.
You can display error message.

Hibernate autumatically create/update the version number when you update/insert any row in the table.

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

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

12.What are the general considerations or best practices for defining your Hibernate persistent classes?

1.You must have a default no-argument constructor for your persistent classes and there should be getXXX() (i.e accessor/getter) and setXXX( i.e. mutator/setter) methods for all your persistable instance variables.

2.You should implement the equals() and hashCode() methods based on your business key and it is important not to use the id field in your equals() and hashCode() definition if the id field is a surrogate key (i.e. Hibernate managed identifier). This is because the Hibernate only generates and sets the field when saving the object.


3. It is recommended to implement the Serializable interface. This is potentially useful if you want to migrate around a multi-processor cluster.
4.The persistent class should not be final because if it is final then lazy loading cannot be used by creating proxy objects.

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

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

14 .Difference between getCurrentSession() and openSession() in Hibernate ?

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.

Example :
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
}

15 .Difference between session.saveOrUpdate() and session.merge()?

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

17 .How does Value replacement in Message Resource Bundle work?

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

18. Difference between list() and iterate() i9n Hibernate?

If instances are already be in the session or second-level cache iterate() will give better performance.
If they are not already cached, iterate() will be slower
than list() and might require many database hits for a simple query.

19. Deleting persistent objects

Session.delete() will remove an object's state from the database. Of course, your application might still hold
a reference to a deleted object. It's best to think of delete() as making a persistent instance transient.
sess.delete(cat);
20. SQL statements execution order.
1.      all entity insertions, in the same order the corresponding objects were saved using Session.save()
2. all entity updates
3. all collection deletions
4. all collection element deletions, updates and insertions
5. all collection insertions
6. all entity deletions, in the same order the corresponding objects were deleted using Session.delete()

21.  Difference between session.saveOrUpdate() and session.merge();

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

22. SQL Queries In Hibernate..

You may express a query in SQL, using createSQLQuery() and let Hibernate take care of the mapping from
result sets to objects. Note that you may at any time call session.connection() and use the JDBC Connection
directly. If you chose to use the Hibernate API, you must enclose SQL aliases in braces:
List cats = session.createSQLQuery(
"SELECT {cat.*} FROM CAT {cat} WHERE ROWNUM<10 br=""> "cat",
Cat.class
).list();
List cats = session.createSQLQuery(
"SELECT {cat}.ID AS {cat.id}, {cat}.SEX AS {cat.sex}, " +
"{cat}.MATE AS {cat.mate}, {cat}.SUBCLASS AS {cat.class}, ... " +
"FROM CAT {cat} WHERE ROWNUM<10 br=""> "cat",
Cat.class
).list()
SQL queries may contain named and positional parameters, just like Hibernate queries.

23. Criteria Query Two Condition

Criteria Query Two Condition- Example








List of organisation where town equals to pune and status = "A".

List organizationList = session.createCriteria(Organization.class)
.add(Restrictions.eq("town","pune"))
.add(Restrictions.eq("statusCode","A"))
.list();
24 .Equal and Not Equal criteria query.
Equal and Not Equal criteria query- Example







List of organisation where town equals to pune.

List organizationList = session.createCriteria(Organization.class).add(Restrictions.eq("town","pune")).list();

List of organisation where town not equals pune.

List organizationList = session.createCriteria(Organization.class).add(Restrictions.ne("town","pune")).list();
25 Cascade Save or Update in Hibernate ?
Cascade Save or Update - In one to Many- EXAMPLE
PROCESS_TYPE_LOV (PROCESS_TYPE_ID number, PROCESS_TYPE_NAME varchar) - TABLE
PROCESS (PROCESS_ID number,PROCESS_NAME varchar,PROCESS_TYPE_ID number)- TABLE

public class ProcessTypeBean {
    
    private Long processTypeId;
    private String processTypeName;

        
    /**
     * @return Returns the processTypeId.
     */
    public Long getProcessTypeId() {
        return processTypeId;
    }
    /**
     * @param processTypeId The processTypeId to set.
     */
    public void setProcessTypeId(Long processTypeId) {
        this.processTypeId = processTypeId;
    }
    /**
     * @return Returns the processTypeName.
     */
    public String getProcessTypeName() {
        return processTypeName;
    }
    /**
     * @param processTypeName The processTypeName to set.
     */
    public void setProcessTypeName(String processTypeName) {
        this.processTypeName = processTypeName;
    }
    
}

public class ProcessBean {
    
    private Long processId;
    private String processName = "";
    private ProcessTypeBean processType;

    public Long getProcessId() {
        return processId;
    }
    /**
     * @param processId The processId to set.
     */
    public void setProcessId(Long processId) {
        this.processId = processId;
    }
    /**
     * @return Returns the processName.
     */
    public String getProcessName() {
        return processName;
    }
    /**
     * @param processName The processName to set.
     */
    public void setProcessName(String processName) {
        this.processName = processName;
    }
    /**
     * @return Returns the processType.
     */
    public ProcessTypeBean getProcessType() {
        return processType;
    }
    /**
     * @param processType The processType to set.
     */
    public void setProcessType(ProcessTypeBean processType) {
        this.processType = processType;
    }
}

        table="PROCESS">
        
                     length="50" />
        
        


        table="PROCESS_TYPE_LOV">
        
                     type="string" length="50" />
        
    

---------------------------------------------------------------------------------
Save Example Code -

ProcessTypeBean pstype = new ProcessTypeBean();
pstype.setProcessTypeName("Java Process");

ProcessBean process = new ProcessBean();
process.setProcessName("Production")
ProcessBean.setProcessType(pstype);

// session.save(pstype); -- This save not required because of in the mapping file cascade="save-update"
session.save(process); - This will insert both ProcessBean and ProcessTypeBean;
26.Hibernate session.close does _not_ call session.flush ?
session.close() don't call session.flush() before closing the session.
This is the session.close() code in hibernate.jar
public Connection close() throws HibernateException {
        log.trace( "closing session" );
        if ( isClosed() ) {
            throw new SessionException( "Session was already closed" );
        }
        

        if ( factory.getStatistics().isStatisticsEnabled() ) {
            factory.getStatisticsImplementor().closeSession();
        }

        try {
            try {
                if ( childSessionsByEntityMode != null ) {
                    Iterator childSessions = childSessionsByEntityMode.values().iterator();
                    while ( childSessions.hasNext() ) {
                        final SessionImpl child = ( SessionImpl ) childSessions.next();
                        child.close();
                    }
                }
            }
            catch( Throwable t ) {
                // just ignore
            }

            if ( rootSession == null ) {
                return jdbcContext.getConnectionManager().close();
            }
            else {
                return null;
            }
        }
        finally {
            setClosed();
            cleanup();
        }
    }
27. what is lazy fetching in hibernate?
Lazy setting 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.Exampleslazy=true (default)Address child of User class can be made lazy if it is not required frequently.lazy=falseBut you may need to load the Author object for Book parent whenever you deal with the book for online bookshop
28. How to Execute Stored procedure in Hibernate ?
Option 1:
Connection con = null;
try {
con = session.connection();
CallableStatement st = con
.prepareCall("{call your_sp(?,?)}");
st.registerOutParameter(2, Types.INTEGER);
st.setString(1, "some_Seq");
st.executeUpdate();
Option 2:





{ ? = call selectAllEmployees() }


code :
SQLQuery sq = (SQLQuery) session.getNamedQuery("selectAllEmployees_SP");
List results = sq.list();
29. what is the advantage of Hibernate over jdbc?
There are lots
1) If you are using Hibernate then you don't need to learn specific SQL (like oracle,mysql), You have to user POJO class object as a table.
2) Don't need to learn query tuning..Hibernate criteria query automatically tuned the query for best performance.
3) You can use inbuild cache for storing data
4) No need to create own connection pool , we can use c3po . It will give best result...
30 .What is the main advantage of using the hibernate than using the sql
1)      If you are using Hibernate then you don't need to learn specific SQL (like oracle,mysql), You have to user POJO class object as a table.

2) Don't need to learn query tuning..Hibernate criteria query automatically tuned the query for best performance.

3) You can use inbuild cache for storing data

4) No need to create own connection pool , we can use c3po . It will give best result...

5> Don't need any join query which reduce performance and complex. Using hibernate you have to define in bean and hbm.xml file.

6> You can add filter in Hibernate which exceute before you query fires and get the best performance

7> EhCache is used for 2nd level cache to store all the redefind data like country table ..

31 .How are joins handled using Hinernate.
Best is use Criteria query
Example -
You have parent class
public class Organization {
private long orgId;
private List messages;
}
Child class
public class Message {
    private long messageId;
private Organization organization;
}

.hbm.xml file



            
                             class="com.bean.Message" />
        







    


Get all the messages from message table where organisation id =

Criteria query is :
session.createCriteria(Message.class).createAlias("organization","org").
            add(Restrictions.eq("org.orgId",new Long(orgId))).add(Restrictions.in("statusCode",status)).list();

you can get all the details in hibernate website.
http://www.hibernate.org/hib_docs/reference/en/html/associations.html
>
Its just like RDBMS joining. After joining two or more tables we are retriving values from different tables.

In HQL, The tables are our Value Objects (VOs). when we apply join on two more VOs we got a result list which contains values from different VOs. How to hold these values. There is no VO is available for holding these dynamically created result list.

So, create a POJO class to hold this result. when you are querying form one or more VOs put the result list into the newly created VO.

Eg:

select new joinVO (userVO.usercode, UserVO.Username,subjectVo.SubjectName) from UserVO, subjectVO where ......


32. how to create primary key using hibernate?




increment generator class automatically generate the primary key for you.

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


1) What is Hibernate?

Hibernate is a powerful, high performance object/relational persistence and query service. This lets the users to develop persistent classes following object-oriented principles such as association, inheritance, polymorphism, composition, and collections.

2) What is ORM?

ORM stands for Object/Relational mapping. It is the programmed and translucent perseverance of objects in a Java application in to the tables of a relational database using the metadata that describes the mapping between the objects and the database. It works by transforming the data from one representation to another.

3) What does an ORM solution comprises of?

  • It should have an API for performing basic CRUD (Create, Read, Update, Delete) operations on objects of persistent classes
  • Should have a language or an API for specifying queries that refer to the classes and the properties of classes
  • An ability for specifying mapping metadata
  • It should have a technique for ORM implementation to interact with transactional objects to perform dirty checking, lazy association fetching, and other optimization functions

4) What are the different levels of ORM quality?

There are four levels defined for ORM quality.
  1. Pure relational
  2. Light object mapping
  3. Medium object mapping
  4. Full object mapping

5) What is a pure relational ORM?

The entire application, including the user interface, is designed around the relational model and SQL-based relational operations.

6) What is a meant by light object mapping?

The entities are represented as classes that are mapped manually to the relational tables. The code is hidden from the business logic using specific design patterns. This approach is successful for applications with a less number of entities, or applications with common, metadata-driven data models. This approach is most known to all.

7) What is a meant by medium object mapping?

The application is designed around an object model. The SQL code is generated at build time. And the associations between objects are supported by the persistence mechanism, and queries are specified using an object-oriented expression language. This is best suited for medium-sized applications with some complex transactions. Used when the mapping exceeds 25 different database products at a time.

8) What is meant by full object mapping?

Full object mapping supports sophisticated object modeling: composition, inheritance, polymorphism and persistence. The persistence layer implements transparent persistence; persistent classes do not inherit any special base class or have to implement a special interface. Efficient fetching strategies and caching strategies are implemented transparently to the application.

9) What are the benefits of ORM and Hibernate?

There are many benefits from these. Out of which the following are the most important one.
  1. Productivity – Hibernate reduces the burden of developer by providing much of the functionality and let the developer to concentrate on business logic.
  2. Maintainability – As hibernate provides most of the functionality, the LOC for the application will be reduced and it is easy to maintain. By automated object/relational persistence it even reduces the LOC.
  3. Performance – Hand-coded persistence provided greater performance than automated one. But this is not true all the times. But in hibernate, it provides more optimization that works all the time there by increasing the performance. If it is automated persistence then it still increases the performance.
  4. Vendor independence – Irrespective of the different types of databases that are there, hibernate provides a much easier way to develop a cross platform application.

10) How does hibernate code looks like?

 
               Session session = getSessionFactory().openSession();
               Transaction tx = session.beginTransaction();
               MyPersistanceClass mpc = new MyPersistanceClass ("Sample App");
               session.save(mpc);
               tx.commit();
               session.close();

11) What is a hibernate xml mapping document and how does it look like?

In order to make most of the things work in hibernate, usually the information is provided in an xml document. This document is called as xml mapping document. The document defines, among other things, how properties of the user defined persistence classes’ map to the columns of the relative tables in database.
 
               xml version="1.0"?>
               
               
               
                  
                     
                               <generator class="increment"/>
                     
                     
                     
                  
               
Everything should be included under tag. This is the main tag for an xml mapping document.

12) Show Hibernate overview?

13) What the Core interfaces are of hibernate framework?

There are many benefits from these. Out of which the following are the most important one.
  1. Session Interface – This is the primary interface used by hibernate applications. The instances of this interface are lightweight and are inexpensive to create and destroy. Hibernate sessions are not thread safe.
  2. SessionFactory Interface – This is a factory that delivers the session objects to hibernate application. Generally there will be a single SessionFactory for the whole application and it will be shared among all the application threads.
  3. Configuration Interface – This interface is used to configure and bootstrap hibernate. The instance of this interface is used by the application in order to specify the location of hibernate specific mapping documents.
  4. Transaction Interface – This is an optional interface but the above three interfaces are mandatory in each and every application. This interface abstracts the code from any kind of transaction implementations such as JDBC transaction, JTA transaction.
  5. Query and Criteria Interface – This interface allows the user to perform queries and also control the flow of the query execution.

14) What are Callback interfaces?

These interfaces are used in the application to receive a notification when some object events occur. Like when an object is loaded, saved or deleted. There is no need to implement callbacks in hibernate applications, but they’re useful for implementing certain kinds of generic functionality.

15) What are Extension interfaces?

When the built-in functionalities provided by hibernate is not sufficient enough, it provides a way so that user can include other interfaces and implement those interfaces for user desire functionality. These interfaces are called as Extension interfaces.

16) What are the Extension interfaces that are there in hibernate?

There are many extension interfaces provided by hibernate.
  • ProxyFactory interface - used to create proxies
  • ConnectionProvider interface – used for JDBC connection management
  • TransactionFactory interface – Used for transaction management
  • Transaction interface – Used for transaction management
  • TransactionManagementLookup interface – Used in transaction management.
  • Cahce interface – provides caching techniques and strategies
  • CacheProvider interface – same as Cache interface
  • ClassPersister interface – provides ORM strategies
  • IdentifierGenerator interface – used for primary key generation
  • Dialect abstract class – provides SQL support

17) What are different environments to configure hibernate?

There are mainly two types of environments in which the configuration of hibernate application differs.
  1. Managed environment – In this kind of environment everything from database connections, transaction boundaries, security levels and all are defined. An example of this kind of environment is environment provided by application servers such as JBoss, Weblogic and WebSphere.
  2. Non-managed environment – This kind of environment provides a basic configuration template. Tomcat is one of the best examples that provide this kind of environment.

18) What is the file extension you use for hibernate mapping file?

The name of the file should be like this : filenam.hbm.xml
The filename varies here. The extension of these files should be “.hbm.xml”.
This is just a convention and it’s not mandatory. But this is the best practice to follow this extension.

19) What do you create a SessionFactory?

 
               Configuration cfg = new Configuration();
               cfg.addResource("myinstance/MyConfig.hbm.xml");
               cfg.setProperties( System.getProperties() );
               SessionFactory sessions = cfg.buildSessionFactory();
First, we need to create an instance of Configuration and use that instance to refer to the location of the configuration file. After configuring this instance is used to create the SessionFactory by calling the method buildSessionFactory().

20) What is meant by Method chaining?

Method chaining is a programming technique that is supported by many hibernate interfaces. This is less readable when compared to actual java code. And it is not mandatory to use this format. Look how a SessionFactory is created when we use method chaining.
 
               SessionFactory sessions = new Configuration()
                   .addResource("myinstance/MyConfig.hbm.xml")
                   .setProperties( System.getProperties() )
                   .buildSessionFactory();
Q. How will you configure Hibernate?

Answer:

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 sevice (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 number 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.


Q. What is a SessionFactory? Is it a thread-safe object?

Answer:

SessionFactory is Hibernates 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();


Q. What is a Session? Can you share a session object between different theads?

Answer:

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


Q. What are the benefits of detached objects?

Answer:


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.

Q. What are the pros and cons of detached objects?

Answer:

Pros:

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


Cons

" In general, working with detached objects is quite cumbersome, and better to not clutter up the session with them if possible. It is better to discard them and re-fetch them on subsequent requests. This approach is not only more portable but also more efficient because - the objects hang around in Hibernate's cache anyway.

" Also from pure rich domain driven design perspective it is recommended to use DTOs (DataTransferObjects) and DOs (DomainObjects) to maintain the separation between Service and UI tiers.


Q. How does Hibernate distinguish between transient (i.e. newly instantiated) and detached objects?

Answer

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

Hibernate uses two different caches for objects: first-level cache and second-level cache..

1) First-level cache

First-level cache always Associates with the Session object. Hibernate uses this cache by default. Here, it processes one transaction after another one, means wont process one transaction many times. Mainly it reduces the number of SQL queries it needs to generate within a given transaction. That is instead of updating after every modification done in the transaction, it updates the transaction only at the end of the transaction.

2) Second-level cache

Second-level cache always associates with the Session Factory object. While running the transactions, in between it loads the objects at the Session Factory level, so that those objects will available to the entire application, don’t bounds to single user. Since the objects are already loaded in the cache, whenever an object is returned by the query, at that time no need to go for a database transaction. In this way the second level cache works. Here we can use query level cache also. Later we will discuss about it.


















The @Entity annotation is used to mark this class as an Entity bean. So the class should atleast have a package scope no-argument constructor.
The @Table annotation is used to specify the table to persist the data. The name attribute refers to the table name. If @Table annotation is not specified then Hibernate will by default use the class name as the table name.
The @Id annotation is used to specify the identifier property of the entity bean. The placement of the @Id annotation determines the default access strategy that Hibernate will use for the mapping. If the @Id annotation is placed over the field, then filed access will be used. Instead if it placed over the getter method of that field, then property access will be used. Here we use property access.
The @GeneratedValue annotation is used to specify the primary key generation strategy to use. If the strategy is not specified by default AUTO will be used.
The @Column annotation is used to specify the details of the column to which a field or property will be mapped. Here the courseId property is mapped to COURSE_ID column in the COURSES table. If the @Column annotation is not specified by default the property name will be used as the column name.
     
Primary key declaration


      @Id
      @GeneratedValue(strategy = GenerationType.AUTO)
      @Column(name = "id")

Hibernate Mapping Many-to-One



Student.hbm.xml is used to create the STUDENT table.
01. version="1.0"?>
02.
03."-//Hibernate/Hibernate Mapping DTD 3.0//EN"
04."http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
05.
06.     name="com.vaannila.student.Student" table="STUDENT">
07.         attribute="class-description">This class contains student details.
08.         name="studentId" type="long" column="STUDENT_ID">
09.             class="native" />
10.        
11.         name="studentName" type="string" length="100" not-null="true" column="STUDENT_NAME" />
12.         name="studentAddress" class="com.vaannila.student.Address" column="STUDENT_ADDRESS" cascade="all" not-null="true" />
13.    
14.