Skip to main content

Hibernate Interview Questions

Q)What are the different Transaction Factories available with Hibernate?
A) There are three types of Tx Factory available in hibernate JDBCTransactionFactory,
JTATransactionFactory and CMTTransactionFactory.

Q) Which one is the default transaction factory in Hibernate 3.2?
A)JDBCTransactionFactory is the default local transaction factory withHibernate 3.2.

Q)Can Hibernate Session Factory be bound to JNDI?
A) Yes, by configuring in hibernate.cfg file, session factory can be bound to initial
context (as defined by properties hibernate.jndi.url and hibernate.jndi.class).
Example:

You have to expose this property hibernate.session_factory_name= java:/hibernate/MySessionFactory in hibaernate.cfg file.
hibernate.jndi.class = com.sun.jndi.fscontext.RefSContextFactory
hibernate.jndi.url = file:/auction/jndi

In side HibernateUtil class


SessionFactory sf = (SessionFactory) new IntialContext().lookup("/hibernate/MySessionFactory")

Q) Can Hibernate be used to call stored procedures and SQL statements?
A) Yes, there are provision in Hibernate 3.2, for defining callable statements and SQL in mapping HBM files.

Example:
  
<?xml version="1.0" encoding="UTF-8"?>

<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">

<hibernate-mapping>
<sql-query name="selectPaymentMaster_SP" callable="true">
<return alias="paymentMaster" class="com.gateway.payment.model.PaymentMaster">

</return>
{ call OC_PAYMENT_METHOD_SEL(?, :paymentTypeCode, :callingAPI) }
</sql-query>
</hibernate-mapping>


  

public List search(PaymentMasterSearch paymentMasterSearchValue) throws PaymentException {
LOGGER.debug(" $---Start of search method in the PaymentMasterService:");
Session sessionObj;
List paymentMasterlist;
try {
if (paymentMasterSearchValue != null) {
sessionObj = HibernateUtil.currentSession();

String keyWord = paymentMasterSearchValue.getSearchKeyWord();
paymentMasterlist = sessionObj.getNamedQuery("selectPaymentMaster_SP")
.setParameter("paymentTypeCode", keyWord)
.setParameter("callingAPI", "OC25")
.list();
HibernateUtil.closeSession();

} else {
LOGGER
.debug(" $--Invalid payment master Search data.");
throw new PaymentException(
"Invalid payment master Search data.");
}

} catch (Exception ex) {
LOGGER.error("Could not find a payment master Record." , ex);
throw new PaymentException("Error in Proccessing the search method.",ex);
}
return paymentMasterlist;
}

Q)Can the custom SQL be defined for creation of Java entityobject by loading values from database tables and populating Java Object?
A) Yes, Javaentity objects can be loaded with custom SQLqueries and can be defined in HBM file in form of HQL (Hibernate Query Language).

Q) What are the different Fetching Strategies available with Hibernate 3.2?
A) There are four different Fetching standards available in Hibernate3.2, as follows: join fetching, select fetching,batch fetching, sub-select fetching.

Q) What are the different types of statistics available in Hibernate 3.2?
A) Different types of statistics like QueryStatistics,CategorizedStatistics, CollectionStatistics, EntityStatistics etc., available in Hibernate 3.2.

Q) How can you get and handle on Hibernate Statistics?
A) If Hibernate is deployed in a JMX enabled Application server, then Hibernate provided a statistics service,that can be registered as MBean with JMX server and be used to retrieve different types of statistics available.Hibernate statistics can be obtained from session factory as well.

Q)
If there are multiple databases to be used to interact with domain classes, how can session factory be able to manage multiple datasources?
A)Each datasource will be configured to each session factory, and to use a single database, a session is created to use database.

Q) What is lazy initialization in Hibernate?
A)When there is an association of one-to-one, or one-to-many, or many-to-many between classes,and on creation of one object, it has to be decided whether to bring associated objects along with this object or not. By setting lazy="true" we instruct Hibernate not to bring the associated object/objects during creation of the required object.By setting lazy="false", it is the reverse, this means we instruct Hibernate to bring all the associated objects also at the time of returning the associating object.

Q) What are the different states of an instance in Hibernate?
A)There are three states that exist for any instance of a class. These are transient, persistent and detached.Those instances that are created but not associated with any session or not saved in database are trasient objects. Those instances that are created and be used in any of the methods like save, saveOrUpdate, update of Session are called persistent objects.Those instances that were used in Session methods like save,saveOrUpdate or update to be inserted or updated in databasetable, and then session is flushed and closed, now these objects are in JVM, but these are not bound to any session are called detached object.

Q)How can certain type of logic executed on execution of CRUD operation of session, without duplicating it across many places in code base?
A)Hibernate Interceptors can be used to receive callback for certain type of events or operations like save, delete, load, update of session. Session Factory level interceptor and session level interceptor. These Interceptors can be used to have code for certain type of logic to be called for every lifecycle method of session.

Q)How can multiple threads access session factory simulteneously to create session instance?
A) session factory is thread-safe, so it is okay to be used by many threads to have session from session factory, but I think session is not thread safe and it should be used by one thread at a time, and after use,session has to be flushed and closed.

Q) How many ways Hibernate manages concurrency ?
A)Hibernate has different ways of managing concurrency.These are automatic versioning, detached object and extended user sessions.

Q) What is the difference between uni-directional and bi-directional associations?
A)uni-directional association allows object creation from one direction only. Bi-directional association allows object querying from both directions of fetching object instances.
A->B, now querying A, can provide information on B as well, based on lazy parameter, but in case of A<->B,querying either A or B, will have value of B or A as well, respectively.
Q)What are the different contextual session in Hibernate?
A)There are three different types of contextual session Hibernate provides, these are JTA session
context, local thread session context and managed session context. JTA session context is
applicable in case Hibernate session is running in JTA (Java Transaction API), request thread
level session scoped applicable in case of local thread session,and managed session,
requires application to open, close and flush session, so creation of session should be handled
by application only.




Comments

Popular posts from this blog

Sorting an List in Java

// Create a list String[] strArray = new String[] {"z", "a", "C"}; List list = Arrays.asList(strArray); // Sort Collections.sort(list); // C, a, z // Case-insensitive sort Collections.sort(list, String.CASE_INSENSITIVE_ORDER); // a, C, z // Reverse-order sort Collections.sort(list, Collections.reverseOrder()); // z, a, C // Case-insensitive reverse-order sort Collections.sort(list, String.CASE_INSENSITIVE_ORDER); Collections.reverse(list); // z, C, a

Linked List Example

/* * Copyright (c) 2000 David Flanagan. All rights reserved. * This code is from the book Java Examples in a Nutshell, 2nd Edition. * It is provided AS-IS, WITHOUT ANY WARRANTY either expressed or implied. * You may study, use, and modify it for any non-commercial purpose. * You may distribute it non-commercially as long as you retain this notice. * For a commercial use license, or to purchase the book (recommended), * visit http://www.davidflanagan.com/javaexamples2. */ /** * This class implements a linked list that can contain any type of object that * implements the nested Linkable interface. Note that the methods are all * synchronized, so that it can safely be used by multiple threads at the same * time. */ public class LinkedList { /** * This interface defines the methods required by any object that can be * linked into a linked list. */ public interface Linkable { public Linkable getNext(); // Returns the next element in the list public...