<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Java Interview Questions &#187; hibernate interview questions</title>
	<atom:link href="http://www.bestjavainterviewquestions.com/category/hibernate-interview-questions/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.bestjavainterviewquestions.com</link>
	<description>Java Interview Questions &#124; Core Java Interview Questions &#124; Advanced Java Interview Questions &#124; EJB Interview Questions &#124; J2EE Interview Questions &#124; Hibernate Interview Questions</description>
	<lastBuildDate>Fri, 03 Feb 2012 10:23:55 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3.1</generator>
		<item>
		<title>What is difference between accessing the table single column and accessing the tabe with multiple column key</title>
		<link>http://www.bestjavainterviewquestions.com/what-is-difference-between-accessing-the-table-single-column-and-accessing-the-tabe-with-multiple-column-key/</link>
		<comments>http://www.bestjavainterviewquestions.com/what-is-difference-between-accessing-the-table-single-column-and-accessing-the-tabe-with-multiple-column-key/#comments</comments>
		<pubDate>Sun, 05 Oct 2008 04:59:40 +0000</pubDate>
		<dc:creator>Ramakrishna</dc:creator>
				<category><![CDATA[hibernate interview questions]]></category>
		<category><![CDATA[accesing single and multiple column tables]]></category>

		<guid isPermaLink="false">http://www.bestjavainterviewquestions.com/?p=436</guid>
		<description><![CDATA[Rep) 1) If the above table has to be accessed using hibernate we must provide a seperae class to hold the values of the columns(multiple) of the primary key.(We can call this class as primary key class) &#8211;&#62;As part of Empaddressid,it will contain the properties such as setId,getId as partid of empno,addrno. 2) In case [...]]]></description>
			<content:encoded><![CDATA[<p><strong>Rep)</strong></p>
<p><strong> </strong>1) If the above table has to be accessed using hibernate we must provide a seperae class to hold the values of the columns(multiple) of the primary key.(We can call this class as primary key class)</p>
<p>&#8211;&gt;As part of Empaddressid,it will contain the properties such as setId,getId as partid of empno,addrno.</p>
<p>2) In case of table with single column as the primary key in the &#8216;hbm file&#8217; we just use &lt;id tag&gt; But In case of the table with multiple columns as the primary key we must use &lt;composite-Id&#8211;&gt; tag as part of the hbm file</p>
<p>3) As part of the primary key class we must provide equals method to return true if both the objects represents the same primary key values and return false if two different object represents two different primary key values</p>
<p>4) As part of the primary key class we must provide the Hash Code method to return the same value for two different objects that are considered as</p>
<p>&#8211;&gt;There is a different between the same and equal</p>
<p>5) The primary key class must implement java.io.serializable Interface.</p>
<h2  class="related_post_title">Random Posts</h2><ul class="related_post"><li>December 12, 2008 -- <a href="http://www.bestjavainterviewquestions.com/url-connection-class/" title="URL Connection Class">URL Connection Class</a> (0)</li><li>September 17, 2008 -- <a href="http://www.bestjavainterviewquestions.com/connecting-our-classsay-x-to-database-using-hibernate/" title="Connecting our Class(say x) to DataBase using Hibernate">Connecting our Class(say x) to DataBase using Hibernate</a> (0)</li><li>December 17, 2008 -- <a href="http://www.bestjavainterviewquestions.com/what-is-abstract-classexplan/" title="What is Abstract Class?Explan">What is Abstract Class?Explan</a> (0)</li><li>October 5, 2008 -- <a href="http://www.bestjavainterviewquestions.com/difference-between-get-and-head-request-methods/" title="Difference between GET and HEAD request methods">Difference between GET and HEAD request methods</a> (0)</li><li>October 27, 2008 -- <a href="http://www.bestjavainterviewquestions.com/final-variables-and-methods/" title="Final Variables and Methods">Final Variables and Methods</a> (0)</li></ul>]]></content:encoded>
			<wfw:commentRss>http://www.bestjavainterviewquestions.com/what-is-difference-between-accessing-the-table-single-column-and-accessing-the-tabe-with-multiple-column-key/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Define create Session and SessionFactory</title>
		<link>http://www.bestjavainterviewquestions.com/define-create-session-and-sessionfactory/</link>
		<comments>http://www.bestjavainterviewquestions.com/define-create-session-and-sessionfactory/#comments</comments>
		<pubDate>Tue, 02 Sep 2008 16:52:57 +0000</pubDate>
		<dc:creator>Ramakrishna</dc:creator>
				<category><![CDATA[hibernate interview questions]]></category>
		<category><![CDATA[createsession()]]></category>

		<guid isPermaLink="false">http://www.bestjavainterviewquestions.com/?p=240</guid>
		<description><![CDATA[Q) How to create Session and SessionFactory in Hibernate? A) Step 1&#62; Put Hibernate properties in the classpath. Step 2&#62; Put .hbm.xml in class path ? Code is Here to create session &#8230; 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; /** * [...]]]></description>
			<content:encoded><![CDATA[<p><strong>Q) How to create Session and SessionFactory in Hibernate?<br />
A)</strong></p>
<p>Step 1&gt; Put Hibernate properties in the classpath.</p>
<p>Step 2&gt; Put .hbm.xml in class path ?</p>
<p>Code is Here to create session &#8230;</p>
<div style="overflow: auto; width: 450px; height: 2500px; background-color: #e9e0da;">
<p>package com.dao;</p>
<p>import java.io.File;<br />
import java.io.FileInputStream;<br />
import java.util.Properties;<br />
import org.apache.log4j.Logger;<br />
import org.hibernate.HibernateException;<br />
import org.hibernate.Session;<br />
import org.hibernate.SessionFactory;<br />
import org.hibernate.Transaction;<br />
import org.hibernate.cfg.Configuration;</p>
<p>/**<br />
*<br />
* @author Satya Das<br />
*/<br />
public class HibernateUtil {<br />
protected static final Logger<br />
logger=Logger.getLogger(HibernateUtil.class);<br />
public static String appHome = &#8220;No&#8221;;</p>
<p>private static SessionFactory sessionFactory;</p>
<p>private static final ThreadLocal threadSession = new ThreadLocal();<br />
private static final ThreadLocal threadTransaction=new ThreadLocal();</p>
<p>/**<br />
* Initialize Hibernate Configuration<br />
*/</p>
<p>public static void initMonitor(){<br />
logger.info(&#8220;Hibernate configure&#8221;);<br />
try {<br />
logger.info(&#8220;appHome&#8221;+appHome);<br />
String path_properties =<br />
appHome+File.separatorChar+&#8221;hibernate.properties&#8221;;<br />
String path_mapping =  appHome+File.separatorChar+&#8221;mapping_classes.mysql.hbm.xml&#8221;;<br />
//String ecache = appHome+File.separatorChar+&#8221;ehcache.xml&#8221;;</p>
<p>Properties propHibernate = new Properties();<br />
propHibernate.load(new FileInputStream(path_properties));</p>
<p>Configuration configuration = new Configuration();<br />
configuration.addFile(path_mapping);<br />
configuration.setProperties(propHibernate);</p>
<p>/* try {<br />
CacheManager.create(ecache);<br />
} catch (CacheException e) {<br />
// logger.logError(e);<br />
}*/</p>
<p>sessionFactory = configuration.buildSessionFactory();</p>
<p>} catch (Throwable ex) {<br />
logger.error(&#8220;Exception in initMonitor&#8221;,ex);<br />
throw new ExceptionInInitializerError(ex);<br />
}<br />
}<br />
/**<br />
* @return a Session Factory Object<br />
*/</p>
<p>public static SessionFactory getSessionFactory() {<br />
logger.info(&#8220;Inside getSessionFactory method&#8221;);<br />
try {<br />
if (sessionFactory == null) {<br />
initMonitor();<br />
}else {<br />
//sessionFactory.getStatistics().logSummary();<br />
}<br />
} catch (Exception e) {<br />
logger.error(&#8220;Exception in getSessionFactory&#8221;,e);<br />
}<br />
return sessionFactory;<br />
}</p>
<p>/**<br />
* @return Session . Start a Session<br />
*/</p>
<p>public static Session getSession() {<br />
Session s = (Session) threadSession.get();<br />
logger.debug(&#8220;session&#8221;+s);<br />
if (s == null) {<br />
s = getSessionFactory().openSession();<br />
threadSession.set(s);<br />
logger.debug(&#8220;session 1 $&#8221;+s);<br />
}<br />
return s;<br />
}</p>
<p>/**<br />
* Close Session<br />
*/</p>
<p>public static void closeSession(){<br />
Session s = (Session) threadSession.get();<br />
threadSession.set(null);<br />
if (s != null &amp;&amp; s.isOpen()) {<br />
s.flush();<br />
s.close();<br />
}<br />
}</p>
<p>/**<br />
* Start a new database transaction.<br />
*/</p>
<p>public static void beginTransaction(){<br />
Transaction tx = null;<br />
if (tx == null) {<br />
tx = getSession().beginTransaction();<br />
threadTransaction.set(tx);<br />
}<br />
}</p>
<p>/**<br />
* Commit the database transaction.<br />
*/</p>
<p>public static void commitTransaction(){<br />
Transaction tx = (Transaction) threadTransaction.get();<br />
try {<br />
if ( tx != null ) {<br />
tx.commit();<br />
}<br />
threadTransaction.set(null);<br />
} catch (HibernateException ex) {<br />
rollbackTransaction();<br />
throw ex;<br />
}<br />
}</p>
<p>/**<br />
* Rollback the database transaction.<br />
*/</p>
<p>public static void rollbackTransaction(){<br />
Transaction tx = (Transaction) threadTransaction.get();<br />
try {<br />
threadTransaction.set(null);<br />
if ( tx != null &amp;&amp; !tx.wasCommitted() &amp;&amp; !tx.wasRolledBack() ) {<br />
tx.rollback();<br />
}<br />
} finally {<br />
closeSession();<br />
}<br />
}<br />
}</p></div>
<h2  class="related_post_title">Random Posts</h2><ul class="related_post"><li>May 22, 2008 -- <a href="http://www.bestjavainterviewquestions.com/core-java-interview-questions/" title="Core Java Interview Questions">Core Java Interview Questions</a> (1)</li><li>May 22, 2008 -- <a href="http://www.bestjavainterviewquestions.com/basic-java-interview-questions-on-lang-package/" title="Basic Java Interview Questions on lang package">Basic Java Interview Questions on lang package</a> (2)</li><li>October 16, 2008 -- <a href="http://www.bestjavainterviewquestions.com/explain-the-instance-variables-in-servlets/" title="Explain the Instance Variables in Servlets">Explain the Instance Variables in Servlets</a> (0)</li><li>July 24, 2008 -- <a href="http://www.bestjavainterviewquestions.com/jsf-important-questions/" title="JSF Important Questions">JSF Important Questions</a> (2)</li><li>August 15, 2008 -- <a href="http://www.bestjavainterviewquestions.com/life-cycle-of-thread/" title="Life Cycle of Thread">Life Cycle of Thread</a> (0)</li></ul>]]></content:encoded>
			<wfw:commentRss>http://www.bestjavainterviewquestions.com/define-create-session-and-sessionfactory/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Difference between getCurrentSession() and openSession()</title>
		<link>http://www.bestjavainterviewquestions.com/difference-between-getcurrentsession-and-opensession/</link>
		<comments>http://www.bestjavainterviewquestions.com/difference-between-getcurrentsession-and-opensession/#comments</comments>
		<pubDate>Tue, 02 Sep 2008 16:36:58 +0000</pubDate>
		<dc:creator>Ramakrishna</dc:creator>
				<category><![CDATA[hibernate interview questions]]></category>
		<category><![CDATA[current-openSession()]]></category>

		<guid isPermaLink="false">http://www.bestjavainterviewquestions.com/?p=236</guid>
		<description><![CDATA[Q.Difference between getCurrentSession() and openSession() in Hibernate ? A) getCurrentSession() : The &#8220;current session&#8221; 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 [...]]]></description>
			<content:encoded><![CDATA[<p><strong>Q.Difference between getCurrentSession() and openSession() in Hibernate ?<br />
A)</strong><br />
<strong>getCurrentSession() :</strong><br />
The &#8220;current session&#8221; refers to a Hibernate Session bound by Hibernate behind the scenes, to the transaction scope.<br />
A Session is opened when <em>getCurrentSession() </em> is called for the first time and closed when the transaction ends.<br />
It is also flushed automatically before the transaction commits. You can call <em>getCurrentSession()</em> as often and anywhere you want as long as the transaction runs.<br />
To enable this strategy in your Hibernate configuration:</p>
<p>set hibernate.transaction.manager_lookup_class to a lookup strategy for your JEE container<br />
set hibernate.transaction.factory_class to org.hibernate.transaction.JTATransactionFactory</p>
<p>Only the Session that you obtained with <em>sf.getCurrentSession()</em> is flushed and closed automatically.</p>
<p><em>Example :</em></p>
<div style="overflow: auto; width: 450px; height: 300px; background-color: #e9e0da;">try {<br />
UserTransaction tx = (UserTransaction)new InitialContext()<br />
.lookup(&#8220;java:comp/UserTransaction&#8221;);</p>
<p>tx.begin();</p>
<p>// Do some work<br />
sf.getCurrentSession().createQuery(&#8230;);<br />
sf.getCurrentSession().persist(&#8230;);</p>
<p>tx.commit();<br />
}<br />
catch (RuntimeException e) {<br />
tx.rollback();<br />
throw e; // or display error message<br />
}</p></div>
<p><strong>openSession() :</strong><br />
If you decide to use manage the Session yourself the go for <em>sf.openSession() </em>, you have to<em> flush()</em> and <em>close()</em> it.<br />
It does not flush and <em>close()</em> automatically.<br />
<em>Example :</em></p>
<div style="overflow: auto; width: 450px; height: 300px; background-color: #e9e0da;">UserTransaction tx = (UserTransaction)new InitialContext()<br />
.lookup(&#8220;java:comp/UserTransaction&#8221;);</p>
<p>Session session = factory.openSession();</p>
<p>try {<br />
tx.begin();</p>
<p>// Do some work<br />
session.createQuery(&#8230;);<br />
session.persist(&#8230;);</p>
<p>session.flush(); // Extra work you need to do</p>
<p>tx.commit();<br />
}<br />
catch (RuntimeException e) {<br />
tx.rollback();<br />
throw e; // or display error message<br />
}<br />
finally {<br />
session.close(); // Extra work you need to do<br />
}</p></div>
<h2  class="related_post_title">Random Posts</h2><ul class="related_post"><li>September 22, 2008 -- <a href="http://www.bestjavainterviewquestions.com/explain-java-main-method/" title="Explain Java Main Method.">Explain Java Main Method.</a> (0)</li><li>October 5, 2008 -- <a href="http://www.bestjavainterviewquestions.com/what-is-unicode-system/" title="What is unicode System">What is unicode System</a> (0)</li><li>July 24, 2008 -- <a href="http://www.bestjavainterviewquestions.com/jsf-important-interview-questions/" title="JSF Important Interview Questions">JSF Important Interview Questions</a> (2)</li><li>July 7, 2008 -- <a href="http://www.bestjavainterviewquestions.com/servlet-important-questions/" title="Servlet Important Questions">Servlet Important Questions</a> (0)</li><li>August 9, 2008 -- <a href="http://www.bestjavainterviewquestions.com/some-important-methos-in-applets/" title="Some important methos in Applets">Some important methos in Applets</a> (0)</li></ul>]]></content:encoded>
			<wfw:commentRss>http://www.bestjavainterviewquestions.com/difference-between-getcurrentsession-and-opensession/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Difference between session.update() and session.lock()</title>
		<link>http://www.bestjavainterviewquestions.com/difference-between-sessionupdate-and-sessionlock/</link>
		<comments>http://www.bestjavainterviewquestions.com/difference-between-sessionupdate-and-sessionlock/#comments</comments>
		<pubDate>Tue, 02 Sep 2008 16:29:34 +0000</pubDate>
		<dc:creator>Ramakrishna</dc:creator>
				<category><![CDATA[hibernate interview questions]]></category>
		<category><![CDATA[session.update()]]></category>

		<guid isPermaLink="false">http://www.bestjavainterviewquestions.com/?p=234</guid>
		<description><![CDATA[Q)  Difference between session.update() and session.lock() in Hibernate ? A) 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 [...]]]></description>
			<content:encoded><![CDATA[<p><strong>Q)  Difference between session.update() and session.lock() in Hibernate ?<br />
</strong></p>
<p><strong>A) </strong>Both of these methods and <strong>saveOrUpdate() </strong>method are intended for reattaching a detached object.<br />
The<strong> session.lock()</strong> 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.<br />
It is the best practice to use either session.update(..) or session.saveOrUpdate().<br />
Use session.lock() only if you are absolutely sure that the<br />
detached object is in sync with your detached object or if it does not matter because<br />
you will be overwriting all the columns that would have changed later on within the same transaction.</p>
<p>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 &#8220;reassociates&#8221; them using Session.update() or Session.saveOrUpdate().</p>
<p><em>// foo is an instance loaded by a previous Session<br />
foo.setProperty(&#8220;bar&#8221;);<br />
session = factory.openSession();<br />
session.saveOrUpdate(foo);<br />
session.flush();<br />
session.connection().commit();<br />
session.close();<br />
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. </em></p>
<h2  class="related_post_title">Random Posts</h2><ul class="related_post"><li>September 7, 2008 -- <a href="http://www.bestjavainterviewquestions.com/define-stateless-session/" title="Define Stateless Session">Define Stateless Session</a> (0)</li><li>April 7, 2011 -- <a href="http://www.bestjavainterviewquestions.com/why-actionservlet-is-singleton-in-struts-framework/" title="Why ActionServlet is Singleton in struts framework?">Why ActionServlet is Singleton in struts framework?</a> (0)</li><li>August 24, 2008 -- <a href="http://www.bestjavainterviewquestions.com/define-stored-procedures/" title="Define Stored Procedures">Define Stored Procedures</a> (0)</li><li>June 23, 2008 -- <a href="http://www.bestjavainterviewquestions.com/java-util-package-2/" title="JAVA UTIL PACKAGE">JAVA UTIL PACKAGE</a> (0)</li><li>February 15, 2009 -- <a href="http://www.bestjavainterviewquestions.com/define-ejb-frame-work/" title="Define EJB frame work">Define EJB frame work</a> (1)</li></ul>]]></content:encoded>
			<wfw:commentRss>http://www.bestjavainterviewquestions.com/difference-between-sessionupdate-and-sessionlock/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Difference between session.save() , session.saveOrUpdate() and session.persist()</title>
		<link>http://www.bestjavainterviewquestions.com/difference-between-sessionsave-sessionsaveorupdate-and-sessionpersist/</link>
		<comments>http://www.bestjavainterviewquestions.com/difference-between-sessionsave-sessionsaveorupdate-and-sessionpersist/#comments</comments>
		<pubDate>Tue, 02 Sep 2008 16:27:30 +0000</pubDate>
		<dc:creator>Ramakrishna</dc:creator>
				<category><![CDATA[hibernate interview questions]]></category>
		<category><![CDATA[session.save()]]></category>

		<guid isPermaLink="false">http://www.bestjavainterviewquestions.com/?p=232</guid>
		<description><![CDATA[Q) Difference between session.save() , session.saveOrUpdate() and session.persist()? A) &#8211;&#62; session.save() : Save does an insert and will fail if the primary key is already persistent. &#8211;&#62; 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 [...]]]></description>
			<content:encoded><![CDATA[<p><strong>Q) Difference between session.save() , session.saveOrUpdate() and session.persist()?<br />
A)</strong><br />
<strong>&#8211;&gt; </strong>session.save() : Save does an insert and will fail if the primary key is already persistent.</p>
<p><strong>&#8211;&gt; </strong>session.saveOrUpdate() : saveOrUpdate does a select first to determine if it needs to do an insert or an update.<br />
Insert data if primary key not exist otherwise update data.</p>
<p><strong>&#8211;&gt; </strong>session.persist() : Does the same like session.save().<br />
But session.save() return Serializable object but session.persist() return void.<br />
session.save() returns the generated identifier (Serializable object) and session.persist() doesn&#8217;t.<br />
<em>For Example :</em><br />
if you do :-<br />
System.out.println(session.save(question));<br />
This will print the generated primary key.<br />
if you do :-<br />
System.out.println(session.persist(question));<br />
Compile time error because session.persist() return void.</p>
<h2  class="related_post_title">Related Post</h2><ul class="related_post"><li>September 20, 2008 -- <a href="http://www.bestjavainterviewquestions.com/difference-between-sessionsave-sessionsaveorupdate-and-sessionpersist-2/" title="Difference between session.save() , session.saveOrUpdate() and session.persist()">Difference between session.save() , session.saveOrUpdate() and session.persist()</a> (0)</li></ul>]]></content:encoded>
			<wfw:commentRss>http://www.bestjavainterviewquestions.com/difference-between-sessionsave-sessionsaveorupdate-and-sessionpersist/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Hibernate Interview Questions</title>
		<link>http://www.bestjavainterviewquestions.com/hibernate-interview-questions-2/</link>
		<comments>http://www.bestjavainterviewquestions.com/hibernate-interview-questions-2/#comments</comments>
		<pubDate>Sat, 12 Jul 2008 18:08:38 +0000</pubDate>
		<dc:creator>Ramakrishna</dc:creator>
				<category><![CDATA[hibernate interview questions]]></category>
		<category><![CDATA[hibernate questions]]></category>

		<guid isPermaLink="false">http://www.bestjavainterviewquestions.com/?p=46</guid>
		<description><![CDATA[Q) What are the most common methods of Hibernate configuration? A) The most common methods of Hibernate configuration are: * Programmatic configuration * XML configuration (hibernate.cfg.xml) Q) What are the important tags of hibernate.cfg.xml? A) An Action Class is an adapter between the contents of an incoming HTTP rest and the corresponding business logic that [...]]]></description>
			<content:encoded><![CDATA[<p><strong>Q) What are the most common methods of Hibernate configuration?<br />
A)</strong> The most common methods of Hibernate configuration are:<br />
* Programmatic configuration<br />
* XML configuration (hibernate.cfg.xml)<br />
<strong><br />
Q) What are the important tags of hibernate.cfg.xml?<br />
A)</strong> An Action Class is an adapter between the contents of an incoming HTTP rest and the corresponding business logic that should be executed to process this rest.</p>
<p><strong>Q) What are the Core interfaces are of Hibernate framework?<br />
A) </strong>People who read this also read:<br />
The five core interfaces are used in just about every Hibernate application. Using these interfaces, you can store and retrieve persistent objects and control transactions.<br />
* Session interface<br />
* SessionFactory interface<br />
* Configuration interface<br />
* Transaction interface<br />
* Query and Criteria interfaces<br />
<strong><br />
Q) What role does the Session interface play in Hibernate?<br />
A)</strong> The Session interface is the primary interface used by Hibernate applications. It is a single-threaded, short-lived object representing a conversation between the application and the persistent store. It allows you to create query objects to retrieve persistent objects.</p>
<p>Session session = sessionFactory.openSession();<br />
Session interface role:</p>
<p>* Wraps a JDBC connection<br />
* Factory for Transaction<br />
* Holds a mandatory (first-level) cache of persistent objects, used when navigating the object graph or looking up objects by identifier<br />
<strong><br />
Q) What role does the SessionFactory interface play in Hibernate?<br />
A)</strong> The application obtains Session instances from a SessionFactory. There is typically a single SessionFactory for the whole application—created during application initialization. The SessionFactory caches generate SQL statements and other mapping metadata that Hibernate uses at runtime. It also holds cached data that has been read in one unit of work and may be reused in a future unit of work</p>
<p>SessionFactory sessionFactory = configuration.buildSessionFactory();<br />
<strong><br />
Q) What is the general flow of Hibernate communication with RDBMS?<br />
A) </strong>The general flow of Hibernate communication with RDBMS is :<br />
* Load the Hibernate configuration file and create configuration object. It will automatically load all hbm mapping files<br />
* Create session factory from configuration object<br />
* Get one session from this session factory<br />
* Create HQL Query<br />
* Execute query to get list containing Java objects<br />
<strong><br />
Q) What is Hibernate Query Language (HQL)?<br />
A) </strong>Hibernate offers a query language that embodies a very powerful and flexible mechanism to query, store, update, and retrieve objects from a database. This language, the Hibernate query Language (HQL), is an object-oriented extension to SQL.</p>
<p><strong>Q) How do you map Java Objects with Database tables?<br />
A) </strong><br />
* First we need to write Java domain objects (beans with setter and getter). The variables should be same as database columns.<br />
* Write hbm.xml, where we map java class to table and database columns to Java class variables.</p>
<p>Example :<br />
&lt;hibernate-mapping&gt;<br />
&lt;class name=&#8221;com.test.User&#8221;  table=&#8221;user&#8221;&gt;<br />
&lt;property  column=&#8221;USER_NAME&#8221; length=&#8221;255&#8243;<br />
name=&#8221;userName&#8221; not-null=&#8221;true&#8221;  type=&#8221;java.lang.String&#8221;/&gt;<br />
&lt;property  column=&#8221;USER_PASSWORD&#8221; length=&#8221;255&#8243;<br />
name=&#8221;userPassword&#8221; not-null=&#8221;true&#8221;  type=&#8221;java.lang.String&#8221;/&gt;<br />
&lt;/class&gt;<br />
&lt;/hibernate-mapping&gt;</p>
<p><strong>Q) What Does Hibernate Simplify?<br />
A)</strong> Hibernate simplifies:</p>
<p>* Saving and retrieving your domain objects<br />
* Making database column and table name changes<br />
* Centralizing pre save and post retrieve logic<br />
* Complex joins for retrieving related items<br />
* Schema creation from object model</p>
<p><strong>Q) What’s the difference between load() and get()?<br />
A)</strong> load() vs. get()</p>
<p>load()  :-<br />
Only use the load() method if you are sure that the object exists.<br />
load() method will throw an exception if the unique id is not found in the database.        load() just returns a proxy by default and database won’t be hit until the proxy is first invoked.</p>
<p>get():-<br />
If you are not sure that the object exists, then use one of the get() methods.<br />
get() method will return null if the unique id is not found in the database.<br />
get() will hit the database immediately.<br />
<strong><br />
Q) What is the difference between and merge and update ?<br />
A)</strong>Use update() if you are sure that the session does not contain an already persistent instance with the same identifier, and merge() if you want to merge your modifications at any time without consideration of the state of the session.<br />
<strong><br />
Q) How do you define sequence generated primary key in hibernate?<br />
A)</strong> Using &lt;generator&gt; tag.<br />
Example:-<br />
&lt;id column=&#8221;USER_ID&#8221; name=&#8221;id&#8221; type=&#8221;java.lang.Long&#8221;&gt;<br />
&lt;generator class=&#8221;sequence&#8221;&gt;<br />
&lt;param name=&#8221;table&#8221;&gt;SEQUENCE_NAME&lt;/param&gt;<br />
&lt;generator&gt;<br />
&lt;/id&gt;<br />
<strong><br />
Q) Define cascade and inverse option in one-many mapping?<br />
A) </strong>cascade &#8211; enable operations to cascade to child entities.<br />
cascade=&#8221;all|none|save-update|delete|all-delete-orphan&#8221;<br />
inverse &#8211; mark this collection as the &#8220;inverse&#8221; end of a bidirectional association.<br />
inverse=&#8221;true|false&#8221;<br />
Essentially &#8220;inverse&#8221; indicates which end of a relationship should be ignored, so when persisting a parent who has a collection of children, should you ask the parent for its list of children, or ask the children who the parents are?<br />
<strong><br />
Q) What does it mean to be inverse?<br />
A)</strong> It informs hibernate to ignore that end of the relationship. If the one–to–many was marked as inverse, hibernate would create a child–&gt;parent relationship (child.getParent). If the one–to–many was marked as non–inverse then a child–&gt;parent relationship would be created.<br />
<strong><br />
Q) What do you mean by Named – SQL query?<br />
A) </strong>Named SQL queries are defined in the mapping xml document and called wherever required.<br />
Example:<br />
&lt;sql-query name = &#8220;empdetails&#8221;&gt;<br />
&lt;return alias=&#8221;emp&#8221; class=&#8221;com.test.Employee&#8221;/&gt;<br />
SELECT emp.EMP_ID AS {emp.empid},<br />
emp.EMP_ADDRESS AS {emp.address},<br />
emp.EMP_NAME AS {emp.name}<br />
FROM Employee EMP WHERE emp.NAME LIKE :name<br />
&lt;/sql-query&gt;<br />
Invoke Named Query :<br />
List people = session.getNamedQuery(&#8220;empdetails&#8221;)<br />
.setString(&#8220;TomBrady&#8221;, name)<br />
.setMaxResults(50)<br />
.list();</p>
<p><strong>Q) How do you invoke Stored Procedures?<br />
A)</strong> &lt;sql-query name=&#8221;selectAllEmployees_SP&#8221; callable=&#8221;true&#8221;&gt;<br />
&lt;return alias=&#8221;emp&#8221; class=&#8221;employee&#8221;&gt;<br />
&lt;return-property name=&#8221;empid&#8221; column=&#8221;EMP_ID&#8221;/&gt;<br />
&lt;return-property name=&#8221;name&#8221; column=&#8221;EMP_NAME&#8221;/&gt;<br />
&lt;return-property name=&#8221;address&#8221; column=&#8221;EMP_ADDRESS&#8221;/&gt;<br />
{ ? = call selectAllEmployees() }<br />
&lt;/return&gt;<br />
&lt;/sql-query&gt;</p>
<p><strong>Q) Explain Criteria API<br />
A)</strong> Criteria is a simplified API for retrieving entities by composing Criterion objects. This is a very convenient approach for functionality like &#8220;search&#8221; screens where there is a variable number of conditions to be placed upon the result set.<br />
Example :<br />
List employees = session.createCriteria(Employee.class)<br />
.add(Restrictions.like(&#8220;name&#8221;, &#8220;a%&#8221;) )<br />
.add(Restrictions.like(&#8220;address&#8221;, &#8220;Boston&#8221;))<br />
.addOrder(Order.asc(&#8220;name&#8221;) )<br />
.list();</p>
<p><strong>Q) Define HibernateTemplate?<br />
A) </strong>org.springframework.orm.hibernate.HibernateTemplate is a helper class which provides different methods for querying/retrieving data from the database. It also converts checked HibernateExceptions into unchecked DataAccessExceptions.<br />
<strong><br />
Q) What are the benefits does HibernateTemplate provide?<br />
A) </strong>The benefits of HibernateTemplate are :<br />
* HibernateTemplate, a Spring Template class simplifies interactions with Hibernate Session.<br />
* Common functions are simplified to single method calls.<br />
* Sessions are automatically closed.<br />
* Exceptions are automatically caught and converted to runtime exceptions.<br />
<strong><br />
Q) How do you switch between relational databases without code changes?<br />
A)</strong> Using Hibernate SQL Dialects , we can switch databases. Hibernate will generate appropriate hql queries based on the dialect defined.<br />
<strong><br />
Q) If you want to see the Hibernate generated SQL statements on console, what should we do?<br />
A)</strong> In Hibernate configuration file set as follows:<br />
&lt;property name=&#8221;show_sql&#8221;&gt;true&lt;/property&gt;</p>
<p><strong>Q) What are derived properties?<br />
A) </strong>The properties that are not mapped to a column, but calculated at runtime by evaluation of an expression are called derived properties. The expression can be defined using the formula attribute of the element.<br />
People who read this also read:<br />
Core Java Questions<br />
Spring Questions<br />
SCJP 6.0 Certification<br />
EJB Interview Questions<br />
Servlets Questions</p>
<p><strong>Q) What is component mapping in Hibernate?<br />
A) </strong><br />
* A component is an object saved as a value, not as a reference<br />
* A component can be saved directly without needing to declare interfaces or identifier        properties<br />
* Required to define an empty constructor<br />
* Shared references not supported</p>
<p><strong>Q) What is the difference between sorted and ordered collection in hibernate?<br />
A)</strong> sorted collection vs. order collection<br />
sorted collection :-<br />
A sorted collection is sorting a collection by utilizing the sorting features provided by the Java collections framework. The sorting occurs in the memory of JVM which running Hibernate, after the data being read from database using java comparator.<br />
If your collection is not large, it will be more efficient way to sort it.</p>
<p>order collection :-<br />
Order collection is sorting a collection by specifying the order-by clause for sorting this collection when retrieval.<br />
If your collection is very large, it will be more efficient way to sort it .</p>
<h2  class="related_post_title">Random Posts</h2><ul class="related_post"><li>February 9, 2009 -- <a href="http://www.bestjavainterviewquestions.com/uploading-excel-file-using-jsp/" title="Uploading Excel File  Using Jsp">Uploading Excel File  Using Jsp</a> (0)</li><li>October 5, 2008 -- <a href="http://www.bestjavainterviewquestions.com/difference-between-get-and-head-request-methods/" title="Difference between GET and HEAD request methods">Difference between GET and HEAD request methods</a> (0)</li><li>September 30, 2008 -- <a href="http://www.bestjavainterviewquestions.com/explain-thread-safe-jsp-page-and-there-advantages/" title="Explain Thread-Safe JSP page and there advantages">Explain Thread-Safe JSP page and there advantages</a> (0)</li><li>October 3, 2008 -- <a href="http://www.bestjavainterviewquestions.com/explain-jsp-directives/" title="Explain Jsp Directives">Explain Jsp Directives</a> (0)</li><li>September 17, 2008 -- <a href="http://www.bestjavainterviewquestions.com/example-of-hibernate/" title="Example of Hibernate">Example of Hibernate</a> (0)</li></ul>]]></content:encoded>
			<wfw:commentRss>http://www.bestjavainterviewquestions.com/hibernate-interview-questions-2/feed/</wfw:commentRss>
		<slash:comments>35</slash:comments>
		</item>
		<item>
		<title>Hibernate Interview Questions</title>
		<link>http://www.bestjavainterviewquestions.com/hibernate-interview-questions/</link>
		<comments>http://www.bestjavainterviewquestions.com/hibernate-interview-questions/#comments</comments>
		<pubDate>Sat, 12 Jul 2008 16:10:03 +0000</pubDate>
		<dc:creator>Ramakrishna</dc:creator>
				<category><![CDATA[hibernate interview questions]]></category>

		<guid isPermaLink="false">http://www.bestjavainterviewquestions.com/?p=45</guid>
		<description><![CDATA[Q) What is Hibernate? A) 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. Q) What is ORM? A) ORM stands for Object/Relational mapping. It is the programmed and translucent perseverance of objects in [...]]]></description>
			<content:encoded><![CDATA[<p><strong>Q) What is Hibernate?</strong><br />
A) 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.</p>
<p><strong>Q) What is ORM?</strong><br />
A) 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.</p>
<p><strong>Q) What does an ORM solution comprises of?</strong><br />
A) It should have an API for performing basic CRUD (Create, Read, Update, Delete) operations on objects of persistent classes<br />
Should have a language or an API for specifying queries that refer to the classes and the properties of classes<br />
An ability for specifying mapping metadata<br />
It should have a technique for ORM implementation to interact with transactional objects to perform dirty checking, lazy association fetching, and other optimization functions<br />
<strong><br />
Q) What are the different levels of ORM quality?</strong><br />
A) There are four levels defined for ORM quality.</p>
<p>1.Pure relational<br />
2.Light object mapping<br />
3.Medium object mapping<br />
4.Full object mapping</p>
<p><strong>Q) What is a pure relational ORM?</strong><br />
A) The entire application, including the user interface, is designed around the relational model and SQL-based relational operations.</p>
<p><strong>Q) What is a meant by light object mapping?</strong><br />
A) 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.</p>
<p><strong>Q) What is a meant by medium object mapping?</strong><br />
A) 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.</p>
<p><strong>Q) What is meant by full object mapping?</strong><br />
A) 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.<br />
<strong><br />
Q) What are the benefits of ORM and Hibernate?</strong><br />
A) There are many benefits from these. Out of which the following are the most important one.<br />
1.Productivity – Hibernate reduces the burden of developer by providing much of the functionality and let the developer to concentrate on business logic.<br />
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.<br />
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.<br />
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.</p>
<p><strong>Q) How does hibernate code looks like?</strong><br />
A) Session session = getSessionFactory().openSession();<br />
Transaction tx = session.beginTransaction();<br />
MyPersistanceClass mpc = new MyPersistanceClass (&#8220;Sample App&#8221;);<br />
session.save(mpc);<br />
tx.commit();<br />
session.close();<br />
The Session and Transaction are the interfaces provided by hibernate. There are many other interfaces besides this.</p>
<h2  class="related_post_title">Random Posts</h2><ul class="related_post"><li>August 24, 2008 -- <a href="http://www.bestjavainterviewquestions.com/deployment-descriptor/" title="Deployment Descriptor">Deployment Descriptor</a> (0)</li><li>September 30, 2008 -- <a href="http://www.bestjavainterviewquestions.com/define-jsp-include-and-jsp-forward/" title="Define Jsp-include and Jsp-forward">Define Jsp-include and Jsp-forward</a> (0)</li><li>October 16, 2008 -- <a href="http://www.bestjavainterviewquestions.com/define-jsp/" title="Define JSP">Define JSP</a> (2)</li><li>August 24, 2008 -- <a href="http://www.bestjavainterviewquestions.com/define-earjar-and-war/" title="Define Ear,jar and war">Define Ear,jar and war</a> (0)</li><li>February 15, 2009 -- <a href="http://www.bestjavainterviewquestions.com/write-a-note-on-ejb-frame-work/" title="Write a note on EJB frame work">Write a note on EJB frame work</a> (0)</li></ul>]]></content:encoded>
			<wfw:commentRss>http://www.bestjavainterviewquestions.com/hibernate-interview-questions/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>

