Hibernate Interview Questions
Hibernate Interview Questions
Hibernate Interview Questions
1. What is Hibernate?
file (i.e mapping file per class) because storing large number of persistent classes into
Ans: Hibernate is a powerful, high performance object/relational persistence and query service.
use the same name as the persistent (POJO) class name. For example Account.class will
This lets the users to develop persistent classes following object-oriented principles such as
be used as part of your persistent class code instead of the *.hbm.xml files.
one mapping file can be difficult to manage and maintain. The naming convention is to
2. What is ORM ?
Ans: ORM stands for Object/Relational mapping. It is the programmed and translucent
Ans: The properties that are not mapped to a column, but calculated at runtime by
using the metadata that describes the mapping between the objects and the database.
evaluation of an expression are called derived properties. The expression can be defined
7. Define HibernateTemplate?
Ans: An entity bean always works under the EJB container, which allows reusing of the
object external to the container. An object can not be detached in entity beans and in
provides different methods for querying/retrieving data from the database. It also
implemented.
Pure relational
sorted collection
order collection
Bag
Set
List
Array
Map
abstract the code from a transaction that is implemented such as a JDBC / JTA
Ans: Mapping of classes can be made into a proxy instead of a table. A proxy is
transaction.
returned when actually a load is called on a session. The proxy contains actual method
to load the data. The proxy is created by default by Hibernate, for mapping a class to a
file. The code to invoke JDBC is contained in this class.
Query and Criteria interface: The queries from the user are allowed by this
interface apart from controlling the flow of the query execution.
cache. First-level cache is associated with the Session object, while second-level cache
Ans: Lazy fetching is associated with child objects loading for its parents. While loading
is associated with the SessionFactory object. By default, Hibernate uses first-level cache
the parent, the selection of loading a child object is to be specified / mentioned in the
on a per-transaction basis. Hibernate uses this cache mainly to reduce the number of
hbm.xml file. Hibernate does not load the whole child objects by default. Lazy=true
Ans: Hibernate always tries to first retrieve objects from the session and if this fails it
tries to retrieve them from the second-level cache. If this fails again, the objects are
Ans: Transient objects do not have association with the databases and session objects.
directly loaded from the database. Hibernate's static initialize() method, which populates
They are simple objects and not persisted to the database. Once the last reference is
a proxy object, will attempt to hit the second-level cache before going to the database.
lost, that means the object itself is lost. And of course , garbage collected. The commits
and rollbacks will have no effects on these objects. They can become into persistent
objects through the save method calls of Session object.
The detached object have corresponding entries in the database. These are persistent
keys of the objects returned by queries. Let us have a look how Hibernate uses the
and not connected to the Session object. These objects have the synchronized data with
query cache to retrieve objects. In order to make use of the query cache we have to
the database when the session was closed. Since then, the change may be done in the
database which makes this object stale. The detached object can be reattached after
certain time to another object in order to become persistent again.
Ans:
List l = query.list();
Session Interface: The basic interface for all hibernate applications. The
instances are light weighted and can be created and destroyed without
expensive process.
Ans: Callback interfaces of hibernate are useful in receiving event notifications from
objects. For example, when an object is loaded or deleted, an event is generated and
applications is done by this interface. For the whole application, there will be
generally one SessionFactory and can be shared by all the application threads.
by specifying lazy="false", this second select will only be executed when you actually
Ans: 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
Ans:
Ans: version checking used in hibernate when more then one thread trying to access
Load() method:
same data.
Only use the load() method if you are sure that the object exists.
For example :
load() method will throw an exception if the unique id is not found in the
User A edit the row of the TABLE for update ( In the User Interface changing data This is
database.
user thinking time) and in the same time User B edit the same record for update and
load() just returns a proxy by default and database won't be hit until the proxy
click the update. Then User A click the Update and update done. Chnage made by user B
is first invoked.
is gone. In hibernate you can perevent slate object updatation using version checking.
Get() method:
If you are not sure that the object exists, then use one of the get()methods.
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
get() method will return null if the unique id is not found in the database.
fetch the version number and match with your version number ( on the time of
fetching).
Ans: Read-only: This strategy is useful for data that is read frequently but never
updated. This is by far the simplest and best-performing cache strategy.
Ans:
They carry more overhead than read-only caches. In non-JTA environments, each
getCurrentSession():
The "current session" refers to a Hibernate Session bound by Hibernate behind the
Nonstrict read/write: This strategy does not guarantee that two transactions won't
simultaneously modify the same data. Therefore, it may be most appropriate for data
called for the first time and closed when the transaction ends.
openSession():
Transactional: This is a fully transactional cache that may be used only in a JTA
If you decide to use manage the Session yourself the go for sf.openSession(), you have
environment.
to flush() and close() it. It does not flush and close() automatically.
Ans: It is possible to re-load an object and all its collections at any time, using the
Join fetching - Hibernate retrieves the associated instance or collection in the same
refresh() method. This is useful when database triggers are used to initialize some of
Select fetching - a second SELECT is used to retrieve the associated entity or collection.
Unless you explicitly disable lazy fetching by specifying lazy="false", this second select
Subselect fetching - a second SELECT is used to retrieve the associated collections for all
entities retrieved in a previous query or fetch. Unless you explicitly disable lazy fetching
Ans: session.lock() method of session class is used to reattach an object which has
Ans: Creating Database applications with Java is made simpler with Hibernate. First
been detached earlier. This method of reattaching doesnt check for any data
Plain old java object needs to be written, XML mapping file should be created which
synchronization in database while reattaching the object and hence may lead to lack of
shows relationship between database and class attributes. Hibernate APIs can be used
synchronization in data.
28. What is the difference between the session.update() method and the
session.lock() method ?
Ans: Hibernate can be configured with two types of files out of which
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
hibernate.cfg.xml file for its operating properties such as database dialect, connection
without checking or updating the database on the assumption that the database in sync
string and mapping files. These files are searched on class path.
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
Ans: Mapping description file is the second file which Hibernate uses to configure its
you will be overwriting all the columns that would have changed later on within the
functions. This mapping file has an extension *.hbm which instructs mapping between
same transaction.
Java class and database tables. The usage of mapping description file rests entirely
upon the business entity.
Because of this feature, many threads can access this concurrently and the sessions are
Ans: Transactions denote a work file which can save changes made or revert back the
requested, and also the cache that is immutable of compiled mappings for a specific
database. A SessionFactory will be built only at the time of its startup. In order to
connection, CORBA or JTA. When this session starts several transactions may occur.
access it in the application code, it should be wrapped in singleton. This wrapping makes
the easy accessibility to it in an application code.
field to field mapping, usually this mapping occurs between classes and attributes. After
Ans: This represents hibernate session which perform the manipulation on the database
mapping files they can be persist to the database. Tags can be used to indicate the
entities. Some of the activities performed by session interface are as follows they are
managing the persistence state, fetching persisted ones and management of the
transaction demarcation.
37. What is the effect when a transient mapped object is passed onto a
Sessions save?
Ans: Dirty checking feature of the Hibernate allows users or developers to avoid time
method to become more persistent. Garbage collection and termination of the Java
consuming data base write actions. This feature makes necessary updations and
virtual machine stays as long as it is deleted explicitly. It may head back to its transient
changes to the fields which require a change, remaining fields are left unchanged or
state.
untouched.
38. Explain about version field?
32. Explain the steps involved in creating database applications with Java
Ans: Application level data integrity constants are important if you are making changes
using Hibernate?
versioning protocol is required to support them. Version field usage comes at this stage
Example :
.add(Restrictions.like(name, a%) )
Ans: Some of the advantages which a developer can get from Hibernate are as follows:
.add(Restrictions.like(address, Boston))
.addOrder(Order.asc(name) )
.list();
the greater benefit from hibernate. POJOs can be used in other applications where they
are applicable.
Ans: Mark the class as mutable=false (Default is true),. This specifies that instances
of the class are (not) mutable. Immutable classes, may not be updated or deleted by
the application.
Ans: This function translates a Java class name into file name. This translated file name
is then loaded as an input stream from the Java class loader. This addclass function is
Ans: The key to obtain better performance in any hibernate application is to employ
you to load all your Hibernate documents at a time. These methods simplify code
Ans: HQL stands for Hibernate Query Language. Hibernate allows the user to express
configuration, refactoring, layout, etc. These functions help you to add your hibernate
queries in its own portable SQL extension and this is called as HQL. It also allows the
Ans: This id field corresponds to the surrogate key which is generated by the database.
Ans:
These fields are handled by the id field. Name attribute is used to specify the names of
the field and it should correspond to the method name of getid. This also should
correspond to long type and the values should be stored I the database in the long
column.
{ ? = call selectAllEmployees() }
Programmatic configuration
</return>
</sql-query>
Code:
Ans:
cascade=all|none|save-update|delete|all-delete-orphan
inverse mark this collection as the inverse end of a bidirectional association.
tables. The code is hidden from the business logic using specific design patterns. This
Ans: Criteria is a simplified API for retrieving entities by composing Criterion objects.
This is a very convenient approach for functionality like search screens where there is