Hibernate Interview Questions
Hibernate Interview Questions
Hibernate Interview Questions
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).
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;
}
Step 2.
In the .hbm.xml file
<class name="beans.Campign" table="CAMPIGN" optimistic-lock="version">
</class>
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();
Hibernate autumatically create/update the version number when you update/insert any row in the table
? if another object associated with the session has the same identifier, throw an exception
? if the object's identifier has the value assigned to a newly instantiated object, save() it
? if the object is versioned (by a <version> or <timestamp>), and the version property value is the same
? if there is no persistent instance currently associated with the session, try to load it from the database, or
? the given instance does not become associated with the session, it remains detached
<hibernate-mapping>
<class name="Writer" table="WRITER">
<id name="id" unsaved-value="0">
<generator class="increment"/>
</id>
---------------------------------------------------
public class Story {
private int id;
private String info;
public Story(){
}
Save Example ..
Writer wr = new Writer();
wr.setName("Das");
try {
transaction = session.beginTransaction();
session.save(sp);
transaction.commit();
} catch (Exception e) {
if (transaction != null) {
transaction.rollback();
throw e;
}
} finally {
session.close();
}
}
--------------------------------------------------------------
Event.hbm.xml
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 2.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-2.0.dtd">
<hibernate-mapping>
<class name="Event" table="events">
<id name="id" column="uid" type="long" unsaved-value="null">
<generator class="increment"/>
</id>
<property name="name" type="string" length="100"/>
<set name="speakers" table="event_speakers" cascade="all">
<key column="event_id"/>
<many-to-many class="Speaker"/>
</set>
</class>
</hibernate-mapping>
------------------------------------------------------------------
Speaker.hbm.xml
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 2.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-2.0.dtd">
<hibernate-mapping>
<class name="Speaker" table="speakers">
<id name="id" column="uid" type="long">
<generator class="increment"/>
</id>
<property name="firstName" type="string" length="20"/>
<set name="events" table="event_speakers" cascade="all">
<key column="speaker_id"/>
<many-to-many class="Event"/>
</set>
</class>
</hibernate-mapping>
----------------------------------------------------------------------
Save and Fetch Example
Event event = new Event();
event.setName("Inverse test");
event.setSpeakers(new HashSet());
event.getSpeakers().add(new Speaker("Ram", event));
event.getSpeakers().add(new SpeakerManyToMany("Syam", event));
event.getSpeakers().add(new SpeakerManyToMany("Jadu", event));
session.save(event); /// Save All the Data
When you are creating SessionFactory just add the below steps
Then
sessionFactory = configuration.buildSessionFactory();
ECache.xml is like
<ehcache>
<diskStore path="java.io.tmpdir"/>
<defaultCache
maxElementsInMemory="10000"
eternal="false"
timeToIdleSeconds="120"
timeToLiveSeconds="120"
overflowToDisk="true"
diskPersistent="false"
diskExpiryThreadIntervalSeconds="120"
/>
<cache name="bean.ApplicationBean"
maxElementsInMemory="300"
eternal="false"
overflowToDisk="false"
/>
</ehcache>
What is a Hibernate Session? Can you share a session object between different theads?
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();
2) EJB need container like Weblogic, WebSphare but hibernate don't nned. It can be run on tomcat.
3) Entity Beans does not support OOPS concepts where as Hibernate does.
Proxies are created dynamically by subclassing your object at runtime. The subclass has all the methods of the
parent, and when any of the methods are accessed, the proxy loads up the real object from the DB and calls the
method for you. Very nice in simple cases with no object hierarchy. Typecasting and instanceof work perfectly on
the proxy in this case since it is a direct subclass.
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:
<sql-query name="selectAllEmployees_SP" callable="true">
<return alias="emp" class="employee">
<return-property name="empid" column="EMP_ID"/>
code :
in the struts-config.xml
<action path="/gotoPageB"
parameter="/WEB-INF/pageB.jsp"
type="org.apache.struts.actions.ForwardAction"/>
Example :
Step 1.
Action Class where saveToken() before JSP Page.
First saveToken() then forward to your jsp.
Upon loading the form, invokes saveToken() on the action class to create and store the token key. Struts will store
the generated key in request/session.
return forward;
}
}
Step 2.
If the token successfully created, when view source on the browser you will see the token, the token key is stored as
a hidden field:
In jsp page :
<body>
<form name="MyForm" method="post" action="/dpsubm/getForm/submit.do">
<input type="text" name="name" >
<input type="hidden" name="<%= Constants.TOKEN_KEY %>"
value="<%= session.getAttribute(Action.TRANSACTION_TOKEN_KEY) %>" >
<input type="submit" value="submit">
</form>
</body>
</html>
if(isTokenValid(request))
{
System.out.println("frm.getName()"+frm.getName());
resetToken(request);
}
else
{
System.out.println("frm.getName()"+frm.getName());
System.out.println("Duplicate Submission of the form");
}
return forward;
}
}
return mapping.findForward("success");
}
}
/* com/BAction.java */
...
return mapping.findForward("success");
}
}