Hibernate Interview Questions
Q1. Difference between
session.save() , session.saveOrUpdate() and session.persist()?
Ans. 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 :
System.out.println(session.save(question)); : This will print the generated primary key.
System.out.println(session.persist(question)); : Compile time error because session.persist()
return void.
Q.2 What is the difference between
hibernate and jdbc ?
Ans. 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 supports 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 donot provide 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
connection pool maintained by hibernate.
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.
Q.3 What is lazy fetching in
Hibernate? With Example.
Ans. 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 actually 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
<set name="address" inverse="true"
cascade="delete" lazy="false">
<key column="a_id" />
<one-to-many class="beans Address"/>
</set>
In the above configuration.
If lazy="false" : - when
you load the Employee object that time child object Address 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 Address 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.
Q4. How to prevent concurrent update
in Hibernate?
OR
How to prevent slate object updation
in Hibernate ?
OR
How to handle user think time using
hibernate ?
Ans. 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. Changes made by user B are gone.
In hibernate you can prevent slate object updatation using version checking.
Check the version of the row when you are updating 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
<class
name="beans.Campign" table="CAMPIGN"
optimistic-lock="version">
<id name="campignId" type="long"
column="cid">
<generator class="sequence">
<param name="sequence">CAMPIGN_ID_SEQ</param>
</generator>
</id>
<version name="versionId"
type="long" column="version" />
<property name="name" column="c_name"/>
</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();
You can handle StaleObjectStateException() and do whatever you want.
You can display error message.
Hibernate autoumatically create/update the version number when you
update/insert any row in the table.
Q5. What are the general
considerations or best practices for defining your Hibernate persistent
classes?
Ans. 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.
6. Difference between
session.update() and session.lock() in Hibernate ?
Ans. 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
"re-associates" 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.
Q7. Difference between
session.saveOrUpdate() and session.merge()?
Ans. saveOrUpdate() does the
following:
1) if the object is already persistent in this session, do nothing
2) if another object associated with the session has the same identifier, throw
an exception
3) if the object has no identifier property, save() it
4) if the object's identifier has the value assigned to a newly instantiated
object, save() it
5) if the object is versioned (by a <version> or <timestamp>), and
the version property value is the same value assigned to a newly instantiated
object, save() it
6) otherwise update() the object
merge() is very different:
1) 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
2) if there is no persistent instance currently associated with the session,
try to load it from the database, or create a new persistent instance.
3) the persistent instance is returned
4) the given instance does not become associated with the session, it remains
detached
Q8. Filter in Hibernate with
Example?
Ans. Filter in Hibernate ------
USER ( ID INT, USERNAME VARCHAR, ACTIVATED BOOLEAN) - TABLE
public class User {
private int
id;
private
String username;
private
boolean activated;
public boolean isActivated() {
return activated; }
public void setActivated(boolean activated) {
this.activated = activated; }
public int getId() {
return id; }
public void setId(int id) {
this.id = id; }
public String getUsername() {
return username; }
public void setUsername(String username) {
this.username = username; }
}
-----------------------------------------------------------------
<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping
DTD//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping package=”……”>
<class name="User">
<id name="id" type="int">
<generator class="native"/>
</id>
<property name="username" type="string"
length="32"/>
<property name="activated" type="boolean"/>
<filter name="activatedFilter" condition=":activatedParam =
activated"/>
</class>
<filter-def name="activatedFilter">
<filter-param name="activatedParam" type="boolean"/>
</filter-def>
</hibernate-mapping>
--------------------------------------------------------------------
Now Fetch the User using Filter..
Filter filter = session.enableFilter("activatedFilter");
filter.setParameter("activatedParam",new Boolean(true));
Query query = session.createQuery("from User");
Iterator results = query.iterate();
while (results.hasNext()){
User user = (User) results.next();
System.out.print(user.getUsername() + " is ");
}
Q9. Difference between list() and
iterate() in Hibernate?
Ans. 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.
Q10. Difference between
session.load() and session.get() ?
Ans. The get( ) methods always hit
the database. Meaning, as soon as the call to get( ) occurs, Hibernate
issues an SQL statement to the database in an attempt to fetch the associated
data (usually a row in the database) to rebuild the requested persistent
object. A call to load( ), on the other hand, does not immediately incur
a call to the database. The load( ) method causes a proxy object to be
constructed as a stand-in for the persistent object. It is only after
some state is requested from the proxy that Hibernate issues the appropriate
SQL to the database and builds the real persistent object. When using
get( ), the method will return null if no data exists for the requested
identifier. Since the load( ) method does not immediately retrieve the
object, if no data exists for the identifier used to retrieve the object, an
ObjectNotFoundException is thrown once data is requested of the proxy.
Q11. Deleting persistent objects
Ans. 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);
Q12. Modifying persistent objects?
Ans. DomesticCat cat = (DomesticCat)
sess.load( Cat.class, new Long(69) );
cat.setName("PK");
sess.flush(); // changes to
cat are automatically detected and persisted To Data Base.
Q13. Criteria Query Two Condition
Ans. Criteria Query Two Condition-
Example
<class name="com.bean.Organization"
table="ORGANIZATION">
<id name="orgId" column="ORG_ID"
type="long">
<generator class="native"/>
</id>
<property name="organizationName"
column="ORGANISATION_NAME" type="string"
length="500"/>
<property name="town" column="TOWN"
type="string" length="200"/>
<property name="statusCode" column="STATUS"
type="string" length="1"/>
</class>
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();
Q14. Equal and Not Equal criteria
query.
Ans. Equal and Not Equal criteria
query- Example
<class name="com.bean.Organization"
table="ORGANIZATION">
<id name="orgId" column="ORG_ID"
type="long">
<generator class="native"/>
</id>
<property name="organizationName"
column="ORGANISATION_NAME" type="string"
length="500"/>
<property name="town" column="TOWN"
type="string" length="200"/>
</class>
List of organization where town equals to pune.
List organizationList =
session.createCriteria(Organization.class).add(Restrictions.eq("town","pune")).list();
List of organization where town not equals pune.
List organizationList =
session.createCriteria(Organization.class).add(Restrictions.ne("town","pune")).list();
Q15. Cascade Save or Update in
Hibernate ?
Ans. Cascade Save or Update – In one
to Many-
EXAMPLE
Tables:
PROCESS_TYPE (
PROCESS_TYPE_ID number,
PROCESS_TYPE_NAME varchar)
PROCESS (
PROCESS_ID number,
PROCESS_NAME varchar,
PROCESS_TYPE_ID number)
public class ProcessTypeBean {
private Long processTypeId;
private String processTypeName;
public Long getProcessTypeId() {
return processTypeId;
}
public void setProcessTypeId(Long
processTypeId) {
this.processTypeId =
processTypeId;
}
public String getProcessTypeName() {
return processTypeName;
}
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;
}
public void
setProcessId(Long processId) {
this.processId = processId;
}
public String getProcessName() {
return processName;
}
public void
setProcessName(String processName) {
this.processName = processName;
}
public ProcessTypeBean getProcessType() {
return processType;
}
public void setProcessType(ProcessTypeBean processType)
{
this.processType = processType;
}
}
<class name="com.bean.ProcessBean" table="PROCESS">
<id
name="processId" type="long" column="PROCESS_ID"
/>
<property
name="processName" column="PROCESS_NAME"
type="string"
length="50"
/>
<many-to-one
name="processType" column="PROCESS_TYPE_ID"
class="ProcessTypeBean" cascade="save-update" />
</class>
<class name="com.bean.ProcessTypeBean"
table="PROCESS_TYPE">
<id
name="processTypeId" type="long"
column="PROCESS_TYPE_ID" />
<property
name="processTypeName" column="PROCESS_TYPE_NAME"
type="string"
length="50" />
</class>
---------------------------------------------------------------------------------
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;
Q16. What does session.refresh() do ?
Ans. it is possible to re-load an
object and all its collections at any time, using the refresh() method. This is
useful when database triggers are used to initialize some of the properties of
the object.
For Example –
Triger on cat_name coulmn. Trigger
is updating hit_count coulmn in the same Cat Table. When Insert data into Cat
TABLE trigger update hit_count coulmn to 1. sess.refresh() reload all the data.
No need again to select call.
sess.save(cat);
sess.flush(); //force the SQL INSERT
sess.refresh(cat); //re-read the state (after the trigger executes)
Q17. How to add hbm.xml file in
sessionFactory?
Ans. SessionFactory sf = new
Configuration().addFile("Item.hbm.xml")
.addFile("Bid.hbm.xml").buildSessionFactory();
Q18. How to get JDBC connections in
hibernate?
Ans. User Session.connection()
method to get JDBC Connection.
Q19. How to Execute Stored procedure
in Hibernate ?
Ans. 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:
<sql-query name="selectAllEmployees_SP"
callable="true">
<return alias="emp" class="employee">
<return-property name="empid" column="EMP_ID"/>
<return-property name="name" column="EMP_NAME"/>
<return-property name="address"
column="EMP_ADDRESS"/>
{ ? = call selectAllEmployees() }
</return>
</sql-query>
code :
SQLQuery sq = (SQLQuery)
session.getNamedQuery("selectAllEmployees_SP");
List results = sq.list();
Q20. how to create primary key using
hibernate?
Ans. <id name="userId"
column="USER_ID" type="int">
<generator class="increment"/>
</id>
increment generator class automatically generate the primary key for you.
Q21. What is Hibernate proxy?
Ans. By default Hibernate creates a
proxy for each of the class you map in mapping file. This class contain the
code to invoke JDBC. This class is created by hibernate using CGLIB.
Proxies are created dynamically by sub-classing 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.
Q22. How are joins handled using
Hinernate ?
Ans. Wait
Q23. Hibernate session.close does
_not_ call session.flush ?
Ans. session.close() don't call
session.flush() before closing the session.
Q24. addScalar() method in
hibernate...
Ans. Double max = (Double)
sess.createSQLQuery("select max(cat.weight) as maxWeight from cats
cat").addScalar("maxWeight", Hibernate.DOUBLE).uniqueResult();
addScalar() method confim that maxWeight is always double type.
This way you don't need to check for it is double or not.
-------------------------------------------------------------------------------------------------------
Most of the time Hibernate
“just works”. Therefore when it is not that easy is comes as somewhat of a
surprise. Hibernate documentation says it is easy to use SQL from within
Hibernate, but lets try it.
We can do it with using named SQL queries, or
simply by embedding our SQL instructions directly in the source code.
Embedding example:
SQLCooperationTest.java
public void runQuery(){
SQLQuery q = TestUtilities.getHSession().
createSQLQuery( "SELECT street,
zip FROM sql_addresses");
q.addScalar( "street",
Hibernate.STRING);
q.addScalar( "zip", Hibernate.STRING);
printResults( q );
}
Named SQL call example: SQLCooperationTest.java
public void runNamedQuery(){
SQLQuery q1 = ( SQLQuery )
TestUtilities.getHSession().getNamedQuery("select_address" );
printResults( q1 );
}
and the definition of the named
query is: sql.hbm.xml
<hibernate-mapping
package="com.sourcelabs.hibernate.bhw.bags" >
<sql-query
name="select_address">
<return-scalar
column="street" type="java.lang.String"/>
<return-scalar
column="zip" type="java.lang.String"/>
select street, zip from
sql_addresses
</sql-query>
</hibernate-mapping>
Q25. What is a Hibernate Session?
Can you share a session object between different threads?
Ans. Session is a light weight and a
non-thread safe 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;
}
}
Q26. What are the core components in
Hibernate ?
Ans. SessionFactory
(org.hibernate.SessionFactory)
A thread safe (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)
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!
Q27. What are the Instance states in
Hibernate?
Ans. transient
The instance is not, and has never been associated with any persistence
context. It has no persistent identity(primary key value).
persistent
The instance is currently associated with a persistence context. It has a
persistent identity (primary key value) and, perhaps, a corresponding row in
the database. For a particular persistence context, Hibernate guarantees that
persistent identity is equivalent to Java identity (in-memory location of the
object).
detached
The instance was once associated with a persistence context, but that context
was closed, or the instance was serialized to another process. It has a
persistent identity and, perhaps, a corresponding row in the database. For
detached instances, Hibernate makes no guarantees about the relationship
between persistent identity and Java identity.
Q28. How to set 2nd level cache in
hibernate with EHCache?
Ans.
Q29. How to Identify and Resolve
Hibernate N+1 SELECT's Problems ?
Ans. Let’s assume that you’re
writing code that’d track the price of mobile phones. Now, let’s say you have a
collection of objects representing different Mobile phone vendors
(MobileVendor), and each vendor has a collection of objects representing the
PhoneModels they offer.
To put it simple, there’s exists a
one-to-many relationship between MobileVendor:PhoneModel.
MobileVendor Class
Class MobileVendor{
long vendor_id;
PhoneModel[] phoneModels;
....
}
Okay, so you want to print out all
the details of phone models. A naive O/R implementation would SELECT all mobile
vendors and then do N additional SELECTs for getting the information of
PhoneModel for each vendor.
-- Get all Mobile Vendors
SELECT * FROM MobileVendor;
-- For each MobileVendor, get
PhoneModel details
.SELECT * FROM PhoneModel WHERE
MobileVendor.vendorId=?
As you see, the N+1 problem can
happen if the first query populates the primary object and the second query
populates all the child objects for each of the unique primary objects
returned.
Solution :
Criteria criteria =
session.createCriteria(MobileVendor.class);
criteria.setFetchMode("phoneModels",
FetchMode.EAGER);
our query returns a list of
MobileVendor objects with the phoneModels initialized. Only one query needs to
be run to return all the PhoneModel and MobileVendor information required.
Q30. Disadvantages of Hibernate ?
Ans. Some disadvantages (or inconveniences) I have encountered so far are
1. Not that flexible when it comes to mapping composite-ids (although you can
do a lot). While this is not a fault of Hibernate as composite-ids are
typically used in legacy systems, it can be a pain when attempting to map
legacy tables.
2. Everything is an object. If you need only a portion of data (say, for a
search), you would still have to retrieve the object. However, this is true for
any ORM strategy.
3. In some cases, you will encounter the (n+1) select problem. That is,
Hibernate will execute (n+1) queries for going through a list of records of
size n. There are some mechanisms suggested by Hibernate that can be used to
mitigate this risk.
4. Till Hibernate 3, you cannot map multiple tables to a single class. This has
been fixed in Hibernate 3 using the join tag.