Hibernate Interview Questions And Answers
21.What are the types of inheritance
models in Hibernate?
There are three types of inheritance models in Hibernate:
· Table per class hierarchy
· Table per subclass
· Table per concrete class
22.What is Hibernate Query Language
(HQL)?
Hibernate Query Language is query language which is used to develop the data
independent query language in the application. This HQL queries are not related
to any database. 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.
23.What are the ways to express
joins in HQL?
HQL provides four ways of expressing (inner and outer) joins:-
· An implicit association join
· An ordinary join in the FROM clause
· A fetch join in the FROM clause.
· A theta-style join in the
WHERE clause.
24 . Transaction with plain JDBC in
Hibernate ?
If you don't have JTA and don't want
to deploy it along with your application, you will usually have to fall back to
JDBC transaction demarcation. Instead of calling the JDBC API you better use
Hibernate's Transaction and the built-in session-per-request functionality:
To enable the thread-bound strategy in your Hibernate configuration:
set hibernate.transaction.factory_class to org.hibernate.transaction.JDBCTransactionFactory
To enable the thread-bound strategy in your Hibernate configuration:
set hibernate.transaction.factory_class to org.hibernate.transaction.JDBCTransactionFactory
set
hibernate.current_session_context_class to thread
Session session = factory.openSession();
Transaction tx = null;
try {
tx = session.beginTransaction();
// Do some work
session.load(...);
session.persist(...);
tx.commit(); // Flush happens automatically
}
catch (RuntimeException e) {
tx.rollback();
throw e; // or display error message
}
finally {
session.close();
}
Session session = factory.openSession();
Transaction tx = null;
try {
tx = session.beginTransaction();
// Do some work
session.load(...);
session.persist(...);
tx.commit(); // Flush happens automatically
}
catch (RuntimeException e) {
tx.rollback();
throw e; // or display error message
}
finally {
session.close();
}
25 . What are the
general considerations or best practices for defining your Hibernate persistent
classes?
1.You must have a
default no-argument constructor for your persistent classes and there should be getXXX()and setXXX()
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.
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.
26 . Difference
between session.update() and session.lock() in Hibernate ?
The session.update
method is used to update the persistence object in the in the database.
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.
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.
27.What are the
Collection types in Hibernate ?
· Set
· List
· Array
· Map
· Bag
28.What is the
difference between sorted and ordered collection in hibernate?
sorted collection vs. order collection :-
sorted collection
|
order collection
|
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.
|
Order collection is
sorting a collection by specifying the order-by clause for sorting this
collection when retrieval.
|
If your collection
is not large, it will be more efficient way to sort it.
|
If your collection
is very large, it will be more efficient way to sort it .
|
29.What are the ways
to express joins in HQL?
HQL provides four ways of expressing (inner and
outer) joins:-
· An implicit
association join
· An ordinary join in
the FROM clause
· A fetch join in the
FROM clause.
· A theta-style
join in the WHERE clause.
30.What do you mean by
Named – SQL query?
Named SQL queries are defined in the mapping xml document and called wherever required.
Example:
<sql-query name = "empdetails">
<return alias="emp" class="com.durgasoft.Employee"/>
SELECT emp.EMP_ID AS {emp.empid},
emp.EMP_ADDRESS AS {emp.address},
emp.EMP_NAME AS {emp.name}
FROM Employee EMP WHERE emp.NAME LIKE :name
</sql-query>
Invoke Named Query :
List people = session.getNamedQuery("empdetails")
.setString("TomBrady", name)
.setMaxResults(50)
.list();
List people = session.getNamedQuery("empdetails")
.setString("TomBrady", name)
.setMaxResults(50)
.list();
31.How do you invoke Stored Procedures?
<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>
32.Explain Criteria API ?
The interface org.hibernate.Criteria represents a query against a particular persistent class. The Session is a factory for Criteria instances. 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 a variable number of conditions to be placed upon the result set.
Example :
List employees = session.createCriteria(Employee.class)
.add(Restrictions.like("name", "a%") )
.add(Restrictions.like("address", "Boston"))
.addOrder(Order.asc("name") )
.list();
33.What’s the
difference between load() and get()?
load()
|
get()
|
Only use the load() method
if you are sure that the object exists.
|
If you are not sure
that the object exists, then use one of the get() methods.
|
load() method will
throw an exception if the unique id is not found in the database.
|
get() method will
return null 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.
|
get() will hit the
database immediately.
|
34.What is the
difference between and merge and update ?
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.
35.Define cascade and inverse option in one-many
mapping?
cascade - enable operations to cascade to child entities.
cascade="all|none|save-update|delete|all-delete-orphan"
inverse - mark this collection as the "inverse" end of a bidirectional association.
inverse="true|false"
Essentially "inverse" 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?
36.Define
HibernateTemplate?
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.
37.What are the
benefits does HibernateTemplate provide?
The benefits of HibernateTemplate are :
· HibernateTemplate, a
Spring Template class simplifies interactions with Hibernate Session.
· Common functions are
simplified to single method calls.
· Sessions are
automatically closed.
· Exceptions are
automatically caught and converted to runtime exceptions.
38. How do you switch
between relational databases without code changes?
Using Hibernate SQL Dialects , we can switch databases. Hibernate will generate appropriate hql queries based on the dialect defined.
39.If you want to see
the Hibernate generated SQL statements on console, what should we do?
By using “show_sql” property of the hibernate
configuration file
In Hibernate configuration file set as follows:
<property name="show_sql">true</property>
In Hibernate configuration file set as follows:
<property name="show_sql">true</property>
40.What are derived
properties?
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.
0 comments:
Post a Comment