Hibernate Notes
Hibernate Notes
Notes
&
Interview
Questions-Answers
HISTORY OF HIBERNATE
Hibernate was started in 2001 by Gavin King as an alternative to using EJB2-style Entity Beans. Its
mission back then was to simply offer better persistence capabilities than offered by EJB2 by
simplifying the complexities and allowing for missing features.
Early in 2003, the Hibernate development team began Hibernate2 releases which offered many
significant improvements over the first release and would go on to catapult Hibernate as the "de
facto" standard for persistence in Java.
The current version of Hibernate is Version 3.x. This version introduced new features like a new
Interceptor/Callback architecture, user defined filters, and JDK 5.0 as of 2010 Hibernate 3 (version
3.5.0 and up) is a certified implementation of the Java Persistence API 2.0 specification via a
wrapper for the Core module which provides conformity with the JSR.
HIBERNATE
------------- Hibernate is a Persistence Framework is used to implement persistence logic or database
operations.
Hibernate is the King among all the persistence Framework like JPA, IBatis, TopLink, JDO
etc.
Architecture of Hibernate is Gavin King (from Redhat).
Hibernate is a ORM (Object Relational Mapping) Tool or Framework which simplifies the
Persistence Operations.
When we are implementing persistence logic with JDBC, we need to write the following code :
try{
get the Connection(DataManager/DataSource);
create the required Statement (Statement, PreparedStatement, CallableStatement);
prepared the SQL Statement
submit the query to database (executeXX())
process the result
}
catch(Exception e){
Handling the Exception
}
finally{
cleanup
}
@ In the case of JDBC, we are responsible for write the code for all the above said operations
across the multiple programme.
@ Some JDBC statements are common like load the DataBase, Connection through DriverManager,
catch the Exception and close the all Connection (1, 2, 3, 5, 7) are common across the multiple
program which gives us the code duplication problem.
@ In the case of JDBC, we are responsible take the required resources and close the resources
after using. If we are not closing the resources that may impact the application performance.
@ In the case of JDBC, we are responsible to write SQL statements, If SQL statements are not welltuned that may also impact the application performance.
We write the Hibernate in two ways :
-------------------------------------------Hibernate 3.1 Core (XML Based)
Hibernate 3.2 Annotation (XML Based)
Hibernate Features :
-----------------------1.
Hibernate System responsible for taking the Connections, creating Statement and releasing
the resources.
2.
Hibernate support various Mapping Styles :
i.
Simple Mapping
ii.
Collection Mapping
iii.
Inheritance Mapping
[a]
Table per sub-class Mapping
[b]
Table per class Mapping
[c]
Table per concrete class Mapping
iv.
Association Mapping
[a]
One-to-One Mapping
[b]
One-to-Many Mapping
[c]
Many-to-Many Mapping
v.
Other Mapping.
3.
Hibernate Supports two ways to manage Connection :
[i]
DriverManager Connection
[ii]
DataSource Connection
4.
Hibernate supports two ways to manage Transactions :
[i]
JDBC Transaction
[ii]
JTA Transaction (EJB Container or Spring Container)
5.
Hibernate provides various Primary Key generation algorithm.
6.
Hibernate has in-built support for Batch Updates.
7.
Hibernate provides various Caching mechanisms.
8.
Hibernate provides various Object Oriented Query Language (OOQL) :
[a]
HQL (Hibernate Query Language)
[b]
QBC (Query By Criteria)
[c]
QBE (Query By Example)
9.
Hibernate System uses many Persistent best practices and forces the developer to use them
for better performance.
Hibernate Architecture :
Configuration
Our
Application
Client Code
Connection
Provider
JDBC API
Connection
JNDI API
Transaction
Factory
JTA API
SessionFactory
Session
Transaction
DB
Reposity
JNDI
Reposity
SessionFactory :
-------------------A SessionFactory is an interface available in org.hibernate package. SessionFactory object is MultiThreaded and Long Lived. SessionFactory is clients for connection provider and Transaction Factory.
The SessionFactory is created from a Configuration object, and as its name implies it is a factory for
Session objects. The SessionFactory object is used by all the threads of an application. It is a
thread safe object. The SessionFactory can also provide caching of persistent objects. The main use
of session factory object is to get the session object for the application. SessionFactory hold an
optional (second-level) cache of data that is reusable between transactions, at a process- or
cluster-level. SessionFactorys are immutable. The behaviour of a SessionFactory is controlled by
properties supplied at configuration time. These properties are defined on Environment.
A SessionFactory is usually only built once at startup. SessionFactory should be wrapped in some
kind of singleton so that it can be easily accessed in an application code.
Creating object of SessionFactory :
SessionFactory sessionFactory = new Configuration().configure().buildSessionfactory();
When we call buildSessionFactory() method on Configuration object then following tasks will
happen :
One SessionFactory object is created per database. Multiple SessionFactory objects (each requiring
a separate Configuration) are created when connecting to multiple databases.
HibernateUtil.java Class for one Database
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
public class HibernateUtil {
static SessionFactory factory = null;
static{
Configuration cfg = new Configuration();
cfg = cfg.configure("hibernate.cfg.xml");
factory = cfg.buildSessionFactory();
}
public static SessionFactory getSessionFactory(){
return factory;
}
}
HibernateUtil.java Class for two Databases
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
public class HibernateUtil {
static SessionFactory orafactory = null;
static SessionFactory jlcfactory = null;
static{
Configuration cfg = new Configuration();
Configuration cfg1 = cfg.configure("oracle.cfg.xml");
orafactory = cfg1.buildSessionFactory();
Configuration cfg2 = cfg.configure("mysql.cfg.xml");
jlcfactory = cfg2.buildSessionFactory();
}
public static SessionFactory getSessionFactory(int x){
if(x==1){
return orafactory;
}else{
return jlcfactory;
}
}
Session :
----------This is an interface available in org.hibernate Package. The representation of single unit of work
with the Java application and the persistence database is done by this object. The wrapping of a
JDBC connection is the emphasized role of a Session interface object. This is the major interface
between Java application and Hibernate. This is a runtime interface. The beginning and ending of a
transaction cycle is bounded by the Session interface. The purpose of this interface is to perform
create, read and delete operations for the objects that are mapped with entity classes.
Session session = sessionFactory.openSession();
Transaction :
---------------When Transaction is started, then following tasks will happened :
Session Cache will be created.
Connection will be taken and will be associated with the current session.
While
When We change the Persistence Logic then we may need to change the other Layers of the
Application. This may give maintenance.
Context : When we are interacting with Persistence Storage.
Solution :
Use DAO Design Pattern (J2EE Pattern)
1.
Follow the Interface model.
2.
Centralize the DAO instance creation in Factory DAO class.
3.
DAOs are stateless so create one and only instance for DAO using Singlton Pattern (GOF
Pattern)
------------- Persistence Layer ---------------
Business
Layer
main()
// Client
Code
Integration
Layer
Interface
CustomerDAO{
addCustomer();
}
class
FactoryDAO{
HCD
// Siglton class
}
EIS Layer
class
HibernateCustomer
DAOImpl{
addCustomer(){
// Client Code
}
}
Hibernate
Runtime
System
J
D
B
C
DataBase
Hibernate Util
1.
Making one SessionFactory for entire Application per DataBase.
2.
Reading the data from Hibernate Configuration document and all the mapping document
only once.
3.
Reducing Code duplication.
Hibernate Template
Reducing the code duplication.
Note : Hibernate uses XML document or properties file to define the object / relational mapping.
The ORM File (.hbm file) contains the mapping between the Java object and corresponding
database table.
Hibernate Mapping Type
----------------------------1.
Simple Mapping : When our Persistence Class fields or variables or property of simple
type like Primitives, Wrappers, String, Date etc. then use the Simple Mapping.
2.
3.
4.
2.
@
@
Inheritance Mapping :
-------------------------Hibernate supports the three basic inheritance mapping strategies:
o table per class hierarchy
o table per subclass
o table per concrete class
In addition, Hibernate supports a fourth, slightly different kind of polymorphism:
o implicit polymorphism
It is possible to use different mapping strategies for different branches of the same inheritance
hierarchy. You can then make use of implicit polymorphism to achieve polymorphism across the
whole
hierarchy. However, Hibernate
does
not
support
mixing <subclass>, <joinedsubclass> and<union-subclass> mappings under the same root <class> element. It is possible to
mix together the table per hierarchy and table per subclass strategies under the the
same <class> element, by combining the<subclass> and <join> elements (see below for an
example).
It is possible to define subclass, union-subclass, and joined-subclass mappings in separate mapping
documents directly beneath hibernate-mapping. This allows you to extend a class hierarchy by
adding a new mapping file. You must specify an extends attribute in the subclass mapping, naming
a previously mapped superclass. Previously this feature made the ordering of the mapping
documents important. Since Hibernate3, the ordering of mapping files is irrelevant when using the
extends keyword. The ordering inside a single mapping file still needs to be defined as superclasses
before subclasses.
<hibernate-mapping>
<subclass name="DomesticCat" extends="Cat" discriminator-value="D">
<property name="name" type="string"/>
</subclass>
</hibernate-mapping>
Table per class hierarchy
Suppose we have an interface Payment with the implementors CreditCardPayment, CashPayment,
andChequePayment. The table per hierarchy mapping would display in the following way:
<class name="Payment" table="PAYMENT">
<id name="id" type="long" column="PAYMENT_ID">
<generator class="native"/>
</id>
<discriminator column="PAYMENT_TYPE" type="string"/>
<property name="amount" column="AMOUNT"/>
...
<subclass name="CreditCardPayment" discriminator-value="CREDIT">
<property name="creditCardType" column="CCTYPE"/>
...
</subclass>
<subclass name="CashPayment" discriminator-value="CASH">
...
</subclass>
<subclass name="ChequePayment" discriminator-value="CHEQUE">
...
</subclass>
</class>
Exactly one table is required. There is a limitation of this mapping strategy: columns declared by
the subclasses, such as CCTYPE, cannot have NOT NULL constraints.
Table per subclass
A table per subclass mapping looks like this:
<class name="Payment" table="PAYMENT">
<id name="id" type="long" column="PAYMENT_ID">
<generator class="native"/>
</id>
<property name="amount" column="AMOUNT"/>
...
<joined-subclass name="CreditCardPayment" table="CREDIT_PAYMENT">
<key column="PAYMENT_ID"/>
<property name="creditCardType" column="CCTYPE"/>
...
</joined-subclass>
<joined-subclass name="CashPayment" table="CASH_PAYMENT">
<key column="PAYMENT_ID"/>
...
</joined-subclass>
<joined-subclass name="ChequePayment" table="CHEQUE_PAYMENT">
<key column="PAYMENT_ID"/>
...
</joined-subclass>
</class>
Four tables are required. The three subclass tables have primary key associations to the superclass
table so the relational model is actually a one-to-one association.
Table per subclass: using a discriminator
Hibernate's implementation of table per subclass does not require a discriminator column. Other
object/relational mappers use a different implementation of table per subclass that requires a type
discriminator column in the superclass table. The approach taken by Hibernate is much more
difficult to implement, but arguably more correct from a relational point of view. If you want to use
a discriminator column with the table per subclass strategy, you can combine the use
of <subclass> and <join>, as follows:
<class name="Payment" table="PAYMENT">
<id name="id" type="long" column="PAYMENT_ID">
<generator class="native"/>
</id>
<discriminator column="PAYMENT_TYPE" type="string"/>
<property name="amount" column="AMOUNT"/>
...
<subclass name="CreditCardPayment" discriminator-value="CREDIT">
<join table="CREDIT_PAYMENT">
<key column="PAYMENT_ID"/>
<property name="creditCardType" column="CCTYPE"/>
...
</join>
</subclass>
<subclass name="CashPayment" discriminator-value="CASH">
<join table="CASH_PAYMENT">
<key column="PAYMENT_ID"/>
...
</join>
</subclass>
<subclass name="ChequePayment" discriminator-value="CHEQUE">
<join table="CHEQUE_PAYMENT" fetch="select">
<key column="PAYMENT_ID"/>
...
</join>
</subclass>
</class>
The optional fetch="select" declaration tells Hibernate not to fetch the ChequePayment subclass
data using an outer join when querying the superclass.
Mixing table per class hierarchy with table per subclass
You can even mix the table per hierarchy and table per subclass strategies using the following
approach:
<class name="Payment" table="PAYMENT">
<id name="id" type="long" column="PAYMENT_ID">
<generator class="native"/>
</id>
<discriminator column="PAYMENT_TYPE" type="string"/>
<property name="amount" column="AMOUNT"/>
...
<subclass name="CreditCardPayment" discriminator-value="CREDIT">
<join table="CREDIT_PAYMENT">
<property name="creditCardType" column="CCTYPE"/>
...
</join>
</subclass>
<subclass name="CashPayment" discriminator-value="CASH">
...
</subclass>
<subclass name="ChequePayment" discriminator-value="CHEQUE">
...
</subclass>
</class>
For any of these mapping strategies, a polymorphic association to the root Payment class is
mapped using <many-to-one>.
<many-to-one name="payment" column="PAYMENT_ID" class="Payment"/>
Table per concrete class
There are two ways we can map the table per concrete class strategy. First, you can use<unionsubclass>.
<class name="Payment">
<id name="id" type="long" column="PAYMENT_ID">
<generator class="sequence"/>
</id>
<property name="amount" column="AMOUNT"/>
...
<union-subclass name="CreditCardPayment" table="CREDIT_PAYMENT">
<property name="creditCardType" column="CCTYPE"/>
...
</union-subclass>
<union-subclass name="CashPayment" table="CASH_PAYMENT">
...
</union-subclass>
<union-subclass name="ChequePayment" table="CHEQUE_PAYMENT">
...
</union-subclass>
</class>
Three tables are involved for the subclasses. Each table defines columns for all properties of the
class, including inherited properties.
The limitation of this approach is that if a property is mapped on the superclass, the column name
must be the same on all subclass tables. The identity generator strategy is not allowed in union
subclass inheritance. The primary key seed has to be shared across all unioned subclasses of a
hierarchy.
If your superclass is abstract, map it with abstract="true". If it is not abstract, an additional table
(it defaults to PAYMENT in the example above), is needed to hold instances of the superclass.
Table per concrete class using implicit polymorphism
An alternative approach is to make use of implicit polymorphism:
<class name="CreditCardPayment" table="CREDIT_PAYMENT">
<id name="id" type="long" column="CREDIT_PAYMENT_ID">
<generator class="native"/>
</id>
<property name="amount" column="CREDIT_AMOUNT"/>
...
</class>
<class name="CashPayment" table="CASH_PAYMENT">
<id name="id" type="long" column="CASH_PAYMENT_ID">
<generator class="native"/>
</id>
<property name="amount" column="CASH_AMOUNT"/>
...
</class>
<class name="ChequePayment" table="CHEQUE_PAYMENT">
<id name="id" type="long" column="CHEQUE_PAYMENT_ID">
<generator class="native"/>
</id>
<property name="amount" column="CHEQUE_AMOUNT"/>
...
</class>
Notice that the Payment interface is not mentioned explicitly. Also notice that properties
of Payment are mapped in each of the subclasses. If you want to avoid duplication, consider using
XML entities (for example, [ <!ENTITY allproperties SYSTEM "allproperties.xml"> ] in
the DOCTYPE declaration and&allproperties; in the mapping).
The disadvantage of this approach is that Hibernate does not generate SQL UNIONs when
performing polymorphic queries.
For this mapping strategy, a polymorphic association to Payment is usually mapped using <any>.
<any name="payment" meta-type="string" id-type="long">
<meta-value value="CREDIT" class="CreditCardPayment"/>
<meta-value value="CASH" class="CashPayment"/>
<meta-value value="CHEQUE" class="ChequePayment"/>
<column name="PAYMENT_CLASS"/>
<column name="PAYMENT_ID"/>
</any>
Mixing implicit polymorphism with other inheritance mappings
Since the subclasses are each mapped in their own <class> element, and since Payment is just an
interface), each of the subclasses could easily be part of another inheritance hierarchy. You can still
use polymorphic queries against the Payment interface.
<class name="CreditCardPayment" table="CREDIT_PAYMENT">
<id name="id" type="long" column="CREDIT_PAYMENT_ID">
<generator class="native"/>
</id>
<discriminator column="CREDIT_CARD" type="string"/>
10
Polymorph
Polymorphic Polymorphic
ic manyone-to-one one-to-many
to-one
Polymorph
ic many- Polymorphic load()/get()
to-many
table per
classhierarchy
<many-to- <one-toone>
one>
<one-to-many>
<many-tos.get(Payment.class, id)
many>
table per
subclass
<many-to- <one-toone>
one>
<one-to-many>
<many-tos.get(Payment.class, id)
many>
table per
concrete-class <many-to- <one-to(unionone>
one>
subclass)
table per
concrete class
(implicit
<any>
polymorphism
)
not
supported
<one-to<many-tomany>(forinvers
s.get(Payment.class, id)
many>
e="true"only)
not supported
11
s.createCriteria
<many-to- (Payment.class).add
any>
( Restrictions.idEq(id) ).
uniqueResult()
Association Mapping :
-------------------------# One-to-One Mapping through Core (Uni-Directional Mapping)
Consider the following relationship between Student and Address entity.
* One Student contains one Address.
* One Address belongs to one Student.
To create the STUDENT and ADDRESS table we need to create the following hibernate mapping files.
Student.hbm.xml is used to create the STUDENT table.
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="com.vaannila.student.Student" table="STUDENT" lazy=false>
<id name="studentId" type="long" column="STUDENT_ID">
<generator class="native" />
</id>
<property name="studentName" type="string" column="STUDENT_NAME" />
<many-to-one name="studentAddress"
class="com.vaannila.student.Address"
column="STUDENT_ADDRESS"
not-null="true" cascade="all" unique="true" />
</class>
</hibernate-mapping>
We
use
the many-to-one element
to
create
the
one-to-one
relationship
between
the Studentand Address entities. We do this my making the STUDENT_ADDRESS column unique in
the STUDENT table.
Address.hbm.xml is used to create the ADDRESS table.
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="com.vaannila.student.Address" table="ADDRESS" lazy=false>
12
13
14
Each student record points to a different address record, this illustrates the one-to-one mapping.
According to the relationship a student can have any number of phone numbers.
To create this relationship we need to have a STUDENT, PHONE and STUDENT_PHONE table. The
relational model is shown below.
To create the STUDENT and PHONE table we need to create the following hibernate mapping files.
Student.hbm.xml is used to create the STUDENT and STUDENT_PHONE table.
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="com.vaannila.student.Student" table="STUDENT" lazy=false>
<id name="studentId" type="long" column="STUDENT_ID">
<generator class="native" />
</id>
<property name="studentName" not-null="true"length="100" column="STUDENT_NAME" />
<set name="studentPhoneNumbers" table="STUDENT_PHONE" cascade="all">
<key column="STUDENT_ID" />
<many-to-many column="PHONE_ID" unique="true"class="com.vaannila.student.Phone" />
</set>
</class>
</hibernate-mapping>
we use many-to-many element to create the one-to-many relationship between the Student and
Phone entities. Since a student can have any number of phone numbers we use a collection to hold
the values. In this case we use Set. Many-to-many element is usually used to create many-to-many
relationship, here we place the unique constraint on the PHONE_ID column, this makes the
relationship one-to-many.
Phone.hbm.xml is used to create the PHONE table.
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="com.vaannila.student.Phone" table="PHONE" lazy=false>
<id name="phoneId" type="long" column="PHONE_ID">
15
16
package com.vaannila.student;
public class Main {
public static void main(String[] args) {
Session session = HibernateUtil.getSessionFactory().openSession();
Transaction transaction = null;
try {
transaction = session.beginTransaction();
Set<Phone> phoneNumbers = new HashSet<Phone>();
phoneNumbers.add(new Phone("house","32354353"));
phoneNumbers.add(new Phone("mobile","9889343423"));
Student student = new Student("Eswar", phoneNumbers);
session.save(student);
transaction.commit();
} catch (HibernateException e) {
transaction.rollback();
e.printStackTrace();
} finally {
session.close();
}
}
}
On executing the Main class we will see the following output.
The STUDENT table has one record.
The STUDENT_PHONE table has two records to link the student and phone numbers.
A single student record points to two phone numbers, this illustrates the one-to-many mapping.
# Many-to-one Mapping through Core
--------------------------------------------Consider the following relationship between Student and Address entity.
According to the relationship many students can have the same address.
To create this relationship we need to have a STUDENT and ADDRESS table.
The relational model is shown below.
17
To create the STUDENT and ADDRESS table we need to create the following hibernate mapping files.
Student.hbm.xml is used to create the STUDENT table.
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="com.vaannila.student.Student" table="STUDENT" lazy=false>
<id name="studentId" type="long" column="STUDENT_ID">
<generator class="native" />
</id>
<property name="studentName" length="100" not-null="true" column="STUDENT_NAME" />
<many-to-one
name="studentAddress"
class="com.vaannila.student.Address"
column="STUDENT_ADDRESS" cascade="all" not-null="true" />
</class>
</hibernate-mapping>
The many-to-one element is used to create the many-to-one relationship between
the Studentand Address entities. The cascade option is used to cascade the required operations to
the associated entity. If the cascade option is set to all then all the operations will be cascaded. For
instance when you save a Student object, the associated Address object will also be saved
automatically.
Address.hbm.xml is used to create the ADDRESS table.
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="com.vaannila.student.Address" table="ADDRESS" lazy=false>
<id name="addressId" type="long" column="ADDRESS_ID">
<generator class="native" />
</id>
<property name="street" column="ADDRESS_STREET" length="250" />
<property name="city" column="ADDRESS_CITY" length="50" />
<property name="state" column="ADDRESS_STATE" length="50" />
<property name="zipcode" column="ADDRESS_ZIPCODE" length="10" />
</class>
</hibernate-mapping>
Now create the hibernate configuration file and add all the mapping files.
Hibernate.cfg.hml
Same as Previous
After creating the configuration file, generate java class files using Hibernate Tools.
The following classes will be generated.
Student.java
18
package com.vaannila.student;
public class Student implements java.io.Serializable {
private long studentId;
private String studentName;
private Address studentAddress;
public Student() {}
public Student(String studentName, Address studentAddress) {
this.studentName = studentName;
this.studentAddress = studentAddress;
}
// Setter and Getter
}
Address.java
package com.vaannila.student;
public class Address implements java.io.Serializable {
private
private
private
private
private
long addressId;
String street;
String city;
String state;
String zipcode;
public Address() {
}
public Address(String street, String city, String state, String zipcode) {
this.street = street;
this.city = city;
this.state = state;
this.zipcode = zipcode;
}
// Setter and Getter
}
Create the Main class to run the example.
Main.java
package com.vaannila.student;
public class Main {
public static void main(String[] args) {
Session session = HibernateUtil.getSessionFactory().openSession();
Transaction transaction = null;
try {
transaction = session.beginTransaction();
Address address = new Address("OMR Road", "Chennai", "TN","600097");
//
By using cascade=all option the address need not be saved explicitly when the
student object is persisted the address will be automatically saved.
//session.save(address);
19
Both the student records points to the same address record, this illustrates the many-to-one
mapping.
According to the relationship a student can enroll in any number of courses and the course can
have any number of students.
To create this relationship we need to have a STUDENT, COURSE and STUDENT_COURSE table.
The relational model is shown below.
To create the STUDENT and COURSE tables you need to create the following hibernate mapping files.
Student.hbm.xml is used to create the STUDENT and STUDENT_COURSE table.
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="com.vaannila.student.Student" table="STUDENT" lazy=false>
<id name="studentId" type="long" column="STUDENT_ID">
20
21
Course.java
package com.vaannila.student;
public class Course implements java.io.Serializable {
private long courseId;
private String courseName;
public Course() {
}
public Course(String courseName) {
this.courseName = courseName;
}
// Setter and Getter
}
Create the Main class to run the example.
Main.java
package com.vaannila.student;
public class Main {
public static void main(String[] args) {
Session session = HibernateUtil.getSessionFactory().openSession();
Transaction transaction = null;
try {
transaction = session.beginTransaction();
Set<Course> courses = new HashSet<Course>();
courses.add(new Course("Maths"));
courses.add(new Course("Computer Science"));
Student student1 = new Student("Eswar", courses);
Student student2 = new Student("Joe", courses);
session.save(student1);
session.save(student2);
transaction.commit();
} catch (HibernateException e) {
transaction.rollback();
e.printStackTrace();
} finally {
session.close();
}
}
}
On executing the Main class you will see the following output.
The STUDENT table has two records.
22
The STUDENT_COURSE table has four records to link the student and courses.
Each student has enrolled in the same two courses, this illustrates the many-to-many mapping.
23
</hibernate-mapping>
The component element is used to map all the Address entity fields to the STUDENT table. In
Hibernate terms the Address entity is called the component and it cannot have its own primary key,
it uses the primary key of the enclosing Student entity.
Now create the hibernate configuration file.
hibernate.cfg.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="hibernate.connection.driver_class"> org.mysql.jdbc.Driver
</property>
<property name="hibernate.connection.url"> jdbc:mysql://localhost/school</property>
<property name="hibernate.connection.username">root</property>
<property name="connection.password">sandeep</property>
<property name="connection.pool_size">1</property>
<property name="hibernate.dialect"> org.hibernate.dialect.HSQLDialect </property>
<property name="show_sql">true</property>
<property name="hbm2ddl.auto">update</property>
<mapping resource="com/vaannila/student/Student.hbm.xml"/>
</session-factory>
</hibernate-configuration>
After creating the configuration file, generate java class files using Hibernate Tools.
The following classes will be generated. We will still have a Student and Address class seperately
but they will be mapped to only one table.
Student.java
package com.vaannila.student;
public class Student implements java.io.Serializable {
private long studentId;
private String studentName;
private Address studentAddress;
public Student() {
}
public Student(String studentName) {
this.studentName = studentName;
}
public Student(String studentName, Address studentAddress) {
this.studentName = studentName;
this.studentAddress = studentAddress;
}
// Setter and Getter
}
Address.java
package com.vaannila.student;
public class Address implements java.io.Serializable {
private String street;
private String city;
24
Each student has one address and the values are stored in the same STUDENT table.
25
26
3.
4.
1.
2.
3.
4.
5.
27
1.
2.
3.
4.
Write one custom class which contains composite fields and implements with Serializable:
@Embeddable
public class SID implements Serializable{
private String bid;
private String sid;
// Default Constructor & parameteraized Constructor
// setters-getters method
}
Write one custom class which generate composite key:
public class SIDGenerator{
public static SID getNextSid(String bid){
// write code
}
}
in Student.java (Persistence class)
@Entity
@Table(name=students)
public class Student{
@Id
@Embedded
@AttributeOverrides({
@AttributeOverride(name=bid,column=@Column(name=bid)),
@AttributeOverride(name=sid,column=@Column(name=sid))
})
private SID studebtId;
.
}
in Client class:
// insert record
SID id= SIDGenerator.getNextSid(30);
// 30 is a bId, sId will auto generate.
Student stu=new Student(id,Krishu,Patna,999999);
session.save(stu);
// select record
Student stu=(Student)session.load(Student.class, new SID(30,101));
System.out.println(stu.getStudentId().getBid());
System.out.println(stu.getStudentId().getSid());
System.out.println(stu.getSname());
28
Detached State : When Persistent class object is participated any session operations and removed
from Session Cache then that object is called as Detached Object. The State of that object is called
Detached State. Detached object contains any Identity or Primary Key.
Transaction Management :
-------------------------------Transaction is the process of performing multiple database operations as one Unit with all-nothing
criteria i.e. when all the database operations in the Unit are successful then Transaction is
successful and should be committed. When any one database operation in the unit is failed then
Transaction is failed and should be rolled back.
When we implement Transactions properly in our application, it guarantees ACID Properties.
A - Atomicity
C - Consistency
I - Isolation
D Durability
Atomicity : Definition of Transaction.
Consistency : When we are running the transaction we may enforce business rules as per the
application requirement. Our application should be consistent when any business rule is failed.
Otherwise we may get some inconsistent rules.
Consider the withdraw operation :
1.
Minimum balance is 5 K
2.
Only 5 withdraw per day.
3.
if(ATM){
limit : 50 K
}
if(Branch){
limit : 5 L
}
Isolation : We can run multiple transactions concurrently. These concurrently running multiple
transactions should not disturb other transaction i.e. multiple transactions should run isolately.
Case A
Consider the case where multiple transactions running concurrently and using multiple Account
rows of Accounts Table.
Transaction
Tx1
Tx2
Tx3
->
->
->
Operations
Withdraw from
Withdraw from
Withdraw from
A/c No.
101
102
103
A/c No.
101
102
103
Case B
Consider the case where multiple transaction running concurrently and using single account row of
accounts table.
Account No. : 38746292
1.
Transfer (withdraw)
2.
bank teller (withdraw / deposit)
3.
loan EMI (withdraw)
In Case B, we may get some problems which are called as Transaction Concurrency Problems.
There are three Transaction Concurrency Problems :
29
1.
2.
3.
To Avoid these problems, we have to apply the one of the following required Transaction Isolation
Level :
1.
READ_UNCOMMITTED
2.
READ_COMMITTED
3.
REPEATABLE_READ
4.
SERIALIZABLE
Durability : Our enterprise data should be available for long time (as long as our enterprise is
running). We have to protect our data from crashes, failures, so we have to implement proper
backup and recovery mechanism and proper logging mechanism.
Dirty Read Problem : When Transaction reads the Dirty value (Modified but not Committed) then
we may get some inconsistent results.
To avoid Dirty reads, we have to lock the column (Cell).
To lock the column, we have to apply Isolation Level called READ_COMMITTED.
Repeatable Read Problem : When a Transaction is reading the same row Repeatedly, we may get
different kind of problem is called Repeatable Read Problem.
To avoid Repeatable Read Problem, we have to lock the row.
To Lock the Row, we have to apply Isolation Level called REPETABLE_READ.
Phantom Read Problem : When the Transaction is reading the set of Rows repeatedly, we may
get different set of rows in different reads. This kind of problem is called Phantom Read Problem.
To avoid Phantom Reads, we have to lock the entire Table.
To lock the table, we have to apply Isolation Level called SERIALIZABLE.
Types of Transactions :
1.
2.
Local Transactions
Distributed Transactions
Local Transactions : When the single Database is participating in the Transaction Operations then
it is called as Local Transactions.
Distributed Transactions : When a two or more databases are participating in the Transaction
Operations then it is called as Distributed Transactions
Types of Transactions :
1. Flat Transactions
2. Nested Transactions
Example - Flat Transaction :
begin tx1
op1
op2
op3
end tx2
Example - Nested Transaction :
begin tx1
op1
op2
begin tx2
op3
op4
end tx2
op5
begin tx3
30
op6
op7
end tx3
op8
end tx1
Example Make a Trip : Mon-Fri (Bangalore -> Pune -> Delhi -> Mumbai -> Bangalore)
JDBC Transaction Management
------------------------------------1. Specify the Transaction Boundaries
Connection con = null;
try{
con=.;
con.setAutoCommit(false);
op1;
op2;
op3;
con.commit();
}
catch(Exception e){
if(con != null)
con.rollback;
}
finally{
if(con != null)
con.close();
}
2. Specify the Isolation Levels
con.setTransactionIsolation(1/2/4/8);
Q.
What will happen when we not specifying the Isolation Level ?
Ans : Database Vendor specific Default Transaction Isolation Level will be used.
Q.
How can we get Database Vendor specific Default Transaction Isolation Level ?
Ans : int getDefaultTransactionIsolation() of Database MetaData.
Default Transaction Isolation Level : MySQL 4,
Oracle 2
31
Q.
Repeatable
Read
Phantom
Read
Lock Type
Concurrency
READ_UNCOMMITED
No
No
No
Not Lock
READ_COMMITED
Yes
No
No
Column
REPEATABLE_READ
Yes
Yes
No
Row
SERIALIZABLE
Yes
Yes
Yes
Table
R
e
d
u
c
e
JDBC
Hibernate
JPA
EJB2/EJB3
Spring
Local Tx.
Yes
Yes
Yes
Yes
Yes
Distributed Tx.
No
Yes (CME)
No (Non-CME)
Yes (CME)
No (Non-CME)
Yes
Yes
Flat Tx.
Yes
Yes
Yes
Yes
Yes
Nested Tx.
No
No
No
No
Yes
Full support for relational operations: HQL allows representing SQL queries in the form
of objects. Hibernate Query Language uses Classes and properties instead of tables and
columns.
Return result as Object: The HQL queries return the query result(s) in the form of
object(s), which is easy to use. This elemenates the need of creating the object and
populate the data from result set.
Polymorphic Queries: HQL fully supports polymorphic queries. Polymorphic queries results
the query results along with all the child objects if any.
32
Easy to Learn: Hibernate Queries are easy to learn and it can be easily implemented in the
applications.
Support for Advance features: HQL contains many advance features such as pagination,
fetch join with dynamic profiling, Inner/outer/full joins, Cartesian products. It also supports
Projection, Aggregation (max, avg) and grouping, Ordering, Sub queries and SQL function
calls.
Database independent: Queries written in HQL are database independent (If database
supports the underlying feature).
Hibernate Cache
-------------------Cache is representation of Database near to Application. When we cache the Read mostly data, we
can reduce the No. of round trips between our application server and database server which
increases performance of our application.
In general, we can have 3 types of cache scopes :
1. Trancational Scope Cache
2. Process Scope Cache
3. Clustered Scope Cache.
Trancational Scope Cache : This kind of cache will created whenever the Transaction is started
and Runs as long as Transaction is running. Transactional scope cache will be destroyed whenever
the Transaction ends either by commit or by rollback.
Process Scope Cache : This kind of cache can be accessed by multiple Transactions running in the
Application or process.
Clustered Scope Cache : When our enterprise application is large scale application then we must
use cluster environment where multiple servers will be clustered and integrated with LBS (Load
Balancing Server) for routing the requests. In the case of Clustered Scope Cache, when one node
caches the data then same data will be replicated to other nodes automatically.
Fig. : Hibernate Cache Architecture
First Level Cache :
* When we create a Transaction then we have to process more tasks like :
Configuration
buildSessionFactory
33
openSession
create Transaction
call persistence class object
process all tasks like updation.
* Multiple persistence object store in SessionCache. When tx.commit() method will be invoked then
all transaction store in database and flushing all session object and closing transaction and all.
* Tasks are :
1. Session cache is the first level cache.
2. Session cache is the Transactional Scope Cache.
3. Session cache is enabled by default and should not be disabled.
4. Whenever we insert or update or select or delete the records then those persistence objects will
be placed automatically in session cache.
5. We can remove the persistence object from session cache using evict(obj) &
clear()
Second Level Cache :
Query Cache is the second level cache.
Query Cache can be process scope or cluster scope cache.
Query Cache is disabled by default. You have to enable explicitly if required.
Whenever we execute the Hibernate queries (HQL, QBC etc. select sql statement) then all
the records returned by select statement will be placed in query cache.
Steps to implements Query Cache :
---------------------------------------1. Enable the query cache by writing the following property in hibernate configuration doc.
<property name=hibernate.cache.user_query_cache>true</property>
2. Specify the Required cache provider in hibernate configuration doc.
<property name=hibernate.cache.provider_class>org.hibernate.cache.EhCacheProvider
</property>
Note : Cache provider supported by Hibernate :
1. HashTableCacheProvider
2. EhCacheProvider (for small application)
3. OSCacheProvider (not mostly use)
4. SWarmCacheProvider (not mostly use)
5. TreeCacheProvider (Jboss Cache Provider)
3. Specify the required caching concurrency strategies in Hibernate mapping doc.
<cache usage=xx>
Usage value can be one of the following :
i> read-only
ii> nonstrict-read-write
iii> read-write
iv> transactional
Note : We have to specify the caching concurrency strategies for class, Collections and
Associations.
Example :
class Student{
int cid;
String cname;
Set emails;
-----------}
<class name=Student table= Student>
-----------<cache usage=read-only/>
<property name=cname/>
<set name=email table=emails/>
<cache usage=read-only/>
--------</set>
34
</class>
4. Call setCacheable() method with true value on Query or Criteria or SQLQuery objects.
HQL
Query q=session.createQuery(from Customer);
q.setCacheable(true);
List list=q.list();
QBC
Creteria ct=session.createCriteria(Customer.class);
ct.setCacheable(true);
List list=ct.list();
5. Specify the Storage Implementations and Expiration Policies.
Note : This will change from cache provider to provider.
ehcache.xml (place in src folder)
<ehcache>
<diskstore path=java.io.tmpdir/>
<defaultcache maxElementsIsMemory=100 eternal=false
timeToIdleSeconds=120 timeToLiveSeconds=120
overFlowToDisk=true/>
<ehcache name=helloCache
maxElementsIsMemory=10 eternal=false timeToIdleSeconds=300
timeToLiveSeconds=600 overFlowToDisk=true/>
Caching Concurrency Strategies
-----------------------------------There are four Caching Concurrency Strategies :
* Read-only
* non strict-read-only
* read-write
* transactional
This strategies will allow us to apply the required locking mechanism for the persistence
objects. Which are available in Query cache.
In this case of Process Scope or Clustered Scope Cache, one persistent object can be
accessed by multiple Transaction running con-currently. This may leads to some concurrency
problems like Dirty Read Problem, Repeatable Read Problem and Phantom Read Problem.
To avoid the problems, we have to required Transactional Isolation Levels as shown in Table :
Hibernate Caching Concurrency Strategies :
Concurrency
Strategy
Transactional
Read-write
Non-Strictread-write
Read Only
CME
Non CME
Supports
UNCOMMITED
Supports
COMMITED
Supports
Read
Supports
Serializable
Yes
No
Yes
Yes
Yes
No
Yes
Yes
Yes
Yes
No
No
Yes
Yes
Yes
No
No
No
Yes
Yes
No
No
No
No
35
Query
Cache
Support
Read
only
Cluster
type
Non
strict
Read
only
Read
Write
Transactional
CME
Non
CME
Production
Support
Memory
Yes
Yes
No
Yes
Yes
No
Yes
Yes
No
Memory
Yes
Yes
No
Yes
Yes
No
Yes
Yes
Yes
Memory
Disk
Yes
Yes
No
Yes
Yes
No
Yes
Yes
Yes
Clustered
No
Yes
Yes
Yes
No
No
Yes
Yes
Yes
Clustered
Yes
Yes
Yes
No
No
Yes
Yes
No
Yes
Storage
Type
Filter :
Hibernate3 provides an innovative new approach to handling data with "visibility" rules. A Hibernate
filter is a global, named, parameterized filter that can be enabled or disabled for a particular
Hibernate session.
Hibernate3 has the ability to pre-define filter criteria and attach those filters at
both a class level and a collection level. A filter criteria allows us to define a restriction clause
similar to the existing "where" attribute available on the class and various collection elements.
These filter conditions, however, can be parameterized. The application can then decide at runtime
whether certain filters should be enabled and what their parameter values should be. Filters can be
used like database views, but they are parameterized inside the application.
In order to use filters, they must first be defined and then attached to the appropriate mapping
elements. To define a filter, use the <filter-def/> element within a <hibernate-mapping/> element:
<filter-def name="myFilter">
<filter-param name="myFilterParam" type="string"/>
</filter-def>
This filter can then be attached to a class:
<class name="myClass" ...>
...
<filter name="myFilter" condition=":myFilterParam = MY_FILTERED_COLUMN"/>
</class>
Or, to a collection:
36
<set ...>
<filter name="myFilter" condition=":myFilterParam = MY_FILTERED_COLUMN"/>
</set>
Or, to both or multiples of each at the same time.
The methods on Session are: enableFilter(String filterName), getEnabledFilter(String filterName),
anddisableFilter(String
filterName).
Filters
must
be
enabled
through
use
of
the
Session.enableFilter() method, which returns an instance of the Filter interface. If you used the
simple filter defined above, it would look like this:
session.enableFilter("myFilter").setParameter("myFilterParam", "some-value");
Methods on the org.hibernate.Filter interface do allow the method-chaining common to much of
Hibernate.
We can attach a single filter to more than one class or collection. To do this, you add a <filter> XML
element to each class or collection. The <filter> XML element has two attributes viz. name and
condition. The name references a filter definition (in the sample application it's : statusFilter) while
condition is analogous to a WHERE clause in HQL.
Note: Each <filter> XML element must correspond to a <filter-def> element. It is possible to have
more than one filter for each filter definition, and each class can have more than one filter. Idea is
to define all the filter parameters in one place and then refer them in the individual filter
conditions.
In the java code, we can programmatically enable or disable the filter. By default the Hibernate
Session doesn't have any filters enabled on it.
The Session interface contains the following methods:
37
The two setParameterList() methods are useful for using IN clauses in your filters. If you want to
use BETWEEN clauses, use two different filter parameters with different names.
38
----------------------------------------------------------------------------
Interview Questions-Answers
---------------------------------------------------------------------------1.What is ORM ?
ORM stands for object relational mapping. ORM is the automated persistence of objects in a Java
application to the tables in a relational database.
2.What does ORM consists of ?
An ORM solution consists of the following four pieces:
API for performing basic CURD operations
API to express queries referring to classes
Facilities to specify metadata
Optimization facilities : dirty checking, lazy associations fetching
3.What are the ORM levels ?
The ORM levels are:
Pure relational (stored procedure.)
Light objects mapping (JDBC)
Medium object mapping
Full object Mapping (composition, inheritance, polymorphism, persistence by reachability)
5.Why do you need ORM tools like hibernate?
The main advantage of ORM like hibernate is that it shields developers from messy SQL. Apart from
this, ORM provides following benefits:
Improved productivity
o High-level object-oriented API
o Less Java code to write
o No SQL to write
Improved performance
o Sophisticated caching
o Lazy loading
o Eager loading
Improved maintainability
o A lot less code to write
Improved portability
o ORM framework generates database-specific SQL for you
6.What Does Hibernate Simplify?
Hibernate simplifies:
Saving and retrieving your domain objects
Making database column and table name changes
Centralizing pre save and post retrieve logic
Complex joins for retrieving related items
Schema creation from object model
7.What is the need for Hibernate xml mapping file?
Hibernate mapping file tells Hibernate which tables and columns to use to load and store objects.
Typical mapping file look as follows:
39
40
Transaction interface
Query and Criteria interfaces
get()
Only use the load() method if you are sure that the
object exists.
41
42
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();
23.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.
24.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.
25.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.
26.If you want to see the Hibernate generated SQL statements on console, what should
we do?
In Hibernate configuration file set as follows:
<property name="show_sql">true</property>
27.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.
28.What is component mapping in Hibernate?
A component is an object saved as a value, not as a reference
A component can be saved directly without needing to declare interfaces or identifier
properties
Required to define an empty constructor
Shared references not supported
Example:
43
order collection
Hibernate
44
45
36.How can Hibernate be configured to access an instance variable directly and not
through a setter method ?
By mapping the property with access="field" in Hibernate metadata. This forces hibernate to
bypass the setter method and access the instance variable directly while initializing a newly loaded
object.
37.How can a whole class be mapped as immutable?
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.
38.What is the use of dynamic-insert and dynamic-update attributes in a class mapping?
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.
dynamic-update (defaults to false): Specifies that UPDATE SQL should be generated at
runtime and contain only those columns whose values have changed
dynamic-insert (defaults to false): Specifies that INSERT SQL should be generated at
runtime and contain only the columns whose values are not null.
39.What do you mean by fetching strategy ?
A fetching strategy is the strategy Hibernate will use for retrieving associated objects if the
application needs to navigate the association. Fetch strategies may be declared in the O/R mapping
metadata, or over-ridden by a particular HQL or Criteria query.
40.What is automatic dirty checking?
Automatic dirty checking is a feature that saves us the effort of explicitly asking Hibernate to
update the database when we modify the state of an object inside a transaction.
41.What is transactional write-behind?
Hibernate uses a sophisticated algorithm to determine an efficient ordering that avoids database
foreign key constraint violations but is still sufficiently predictable to the user. This feature is called
transactional write-behind.
42.What are Callback interfaces?
Callback interfaces allow the application to receive a notification when something interesting
happens to an objectfor example, when an object is loaded, saved, or deleted. Hibernate
applications don't need to implement these callbacks, but they're useful for implementing certain
kinds of generic functionality.
44.What are the differences between EJB 3.0 & Hibernate
Hibernate Vs EJB 3.0 :Hibernate
EJB 3.0
46
an Entity
1. What is Hibernate?
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
2.What is ORM ?
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.
3.What are the different levels of ORM quality?
There are four levels defined for ORM
quality.
Pure relational
Light object mapping
Medium object mapping
Full object mapping
4. How will you configure Hibernate?
The configuration files hibernate.cfg.xml (or hibernate.properties) and mapping files *.hbm.xml are
used by the Configuration class to create (i.e. configure and bootstrap hibernate) the
SessionFactory, which in turn creates the Session instances. Session instances are the primary
interface for the persistence service.
" hibernate.cfg.xml (alternatively can use hibernate.properties): These two files are used to
configure the hibernate sevice (connection driver class, connection URL, connection username,
connection password, dialect etc). If both files are present in the classpath then hibernate.cfg.xml
file overrides the settings found in the hibernate.properties file.
" Mapping files (*.hbm.xml): These files are used to map persistent objects to a relational
database. It is the best practice to store each object in an individual mapping file (i.e mapping file
per class) because storing large number of persistent classes into one mapping file can be difficult
to manage and maintain. The naming convention is to use the same name as the persistent (POJO)
class name. For example Account.class will have a mapping file named Account.hbm.xml.
Alternatively hibernate annotations can be used as part of your persistent class code instead of the
*.hbm.xml files.
5. 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.
8 . What is the difference between sorted and ordered collection in hibernate?
sorted collection vs. order collection :sorted collection
order collection
47
java comparator.
If your collection is not large, it will be more
efficient way to sort it.
48
It is also vital that you close your session after your unit of work completes. Note: Keep your
Hibernate Session API handy.
Q. What are the benefits of detached objects?
Detached objects can be passed across layers all the way up to the presentation layer without
having to use any DTOs (Data Transfer Objects). You can later on re-attach the detached objects to
another session.
Q. What are the pros and cons of detached objects?
Pros:
" When long transactions are required due to user think-time, it is the best practice to break the
long transaction up into two or more transactions. You can use detached objects from the first
transaction to carry data all the way up to the presentation layer. These detached objects get
modified outside a transaction and later on re-attached to a new transaction via another session.
Cons
" In general, working with detached objects is quite cumbersome, and better to not clutter up the
session with them if possible. It is better to discard them and re-fetch them on subsequent
requests. This approach is not only more portable but also more efficient because - the objects
hang around in Hibernate's cache anyway.
" Also from pure rich domain driven design perspective it is recommended to use DTOs
(DataTransferObjects) and DOs (DomainObjects) to maintain the separation between Service and
UI tiers.
Q. How does Hibernate distinguish between transient (i.e. newly instantiated) and
detached objects?
" Hibernate uses the version property, if there is one.
" If not uses the identifier value. No identifier value means a new object. This does work only for
Hibernate managed surrogate keys. Does not work for natural keys and assigned (i.e. not managed
by Hibernate) surrogate keys.
" Write your own strategy with Interceptor.isUnsaved().
Q. What is the difference between the session.get() method and the session.load()
method?
Both the session.get(..) and session.load() methods create a persistent object by loading the
required object from the database. But if there was not such object in the database then the
method session.load(..) throws an exception whereas session.get(&) returns null.
Q. What is the difference between the session.update() method and the session.lock()
method?
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.
Note: When you reattach detached objects you need to make sure that the dependent objects are
reatched as well.
Q. How would you reatach detached objects to a session when the same object has
already been loaded into the session?
You can use the session.merge() method call.
Q. 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() (i.e accessor/getter) and setXXX( i.e. mutator/setter) methods for all your persistable
instance variables.
49
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.
5.Use XDoclet tags for generating your *.hbm.xml files or Annotations (JDK 1.5 onwards), which
are less verbose than *.hbm.xml files.
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 should be executed to process this rest.
Q) What are the Core interfaces are of Hibernate framework?
A) People who read this also read:
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.
* Session interface
* SessionFactory interface
* Configuration interface
* Transaction interface
* Query and Criteria interfaces
Q) What role does the Session interface play in Hibernate?
A) The Session interface is the primary interface used by Hibernate applications. It is a singlethreaded, short-lived object representing a conversation between the application and the persistent
store. It allows you to create query objects to retrieve persistent objects.
Session session = sessionFactory.openSession();
Session interface role:
* 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
Q) What role does the SessionFactory interface play in Hibernate?
A) The application obtains Session instances from a SessionFactory. There is typically a single
SessionFactory for the whole applicationcreated 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
SessionFactory sessionFactory = configuration.buildSessionFactory();
Q) What is the general flow of Hibernate communication with RDBMS?
A) The general flow of Hibernate communication with RDBMS is :
* Load the Hibernate configuration file and create configuration object. It will automatically load all
hbm mapping files
* Create session factory from configuration object
* Get one session from this session factory
* Create HQL Query
* Execute query to get list containing Java objects
50
51
52
order collection :Order collection is sorting a collection by specifying the order-by clause for sorting this collection
when retrieval.
If your collection is very large, it will be more efficient way to sort it .
Explain about HibernateTemplate?
Ans: The org.springframework.orm.hibernate.HibernateTemplate class simplifies Hibernate data
access code, and converts checked HibernateExceptions into unchecked DataAccessExceptions,
following the org.springframework.dao exception hierarchy. Uses the same SQLExceptionTranslator
mechanism as JdbcTemplate.
The central method is execute(), supporting Hibernate access code implementing the
HibernateCallback interface. It provides Hibernate Session handling such that neither the
HibernateCallback implementation nor the calling code needs to explicitly care about
retrieving/closing Hibernate Sessions, or handling Session lifecycle exceptions.
What happens when both hibernate.properties and hibernate.cfg.xml are in the
classpath?
Ans: The settings of the XML configuration file will override the settings used in the properties.
What is the use of dynamic-insert and dynamic-update attributes in a class mapping?
Ans: You may declare a persistent class using the class element. The dynamic-insert and dynamicupdate attributes are optional attributes. The dynamic-update (defaults value is false), specifies
that UPDATE SQL should be generated at runtime and contain only those columns whose values
have changed.
The dynamic-insert (defaults value is false), specifies that INSERT SQL should be generated at
runtime and contain only the columns whose values are not null.
What is Connection pools used for in Hibernate?
Ans:
Connection pools are a common way to improve application performance. Rather than opening a
separate connection to the database for each request, the connection pool maintains a collection of
open database connections that are reused. Application servers often provide their own connection
pools using a JNDI DataSource, which Hibernate can take advantage of when configured to use a
DataSource.
When you choose a connection pooling service, you must configure it for your environment.
Hibernate supports configuring connection pools from the hibernate.cfg.xml file. The
connection.provider_class property sets the pooling implementation:
<property name="connection.provider_class">
org.hibernate.connection.C3P0ConnectionProvider
</property>
How will you configure the SessionFactory?
Ans: The Configuration class kicks off the runtime portion of Hibernate. It's used to load the
mapping files and create a SessionFactory for those mapping files. There are three ways to create
and initialize a Configuration object.
This first snippet loads the properties and mapping files defined in the hibernate.cfg.xml file and
creates the SessionFactory:
Configuration cfg =new Configuration();
SessionFactory factory =cfg.configure().buildSessionFactory();
The configure()method tells Hibernate to load the hibernate.cfg.xml file.
The Configuration class can also load mapping documents programmatically:
Configuration cfg =new Configuration();
cfg.addFile("com/manning/hq/ch03/Event.hbm.xml");
Another alternative is to have Hibernate load the mapping document based on the persistent class.
What are the Joined Subclasses in Hibernate?
Ans: Joined subclasses are those that are mapped to a table-per-subclass design rather than a
table-per-hierarchy.
53
54
To obtain a Criteria instance, call createCriteria(), passing the class of the objects you want the
quety to return. This is also called the root entity of the criteria query, the User in this example:
Criteria c = session.createCriteria(User.class);
What are the various built-in-mapping types available in Hibernate?
Ans:
Hibernate built-in mapping types usually share the name of the Java type they map; however, there
may be more than one Hibernate mapping type for a partucular Java type. The various built-inmapping types available in Hibernate are:
* Java primitive mapping types
* Date and time mapping types
* Large object mapping types
* Various JDK mapping types
What are the various built-in concurrency strategies for transaction used in Hibernate?
Ans:
A concurrency strategy is a mediator, it's responsible for storing items of data in the cache and
retrieving them from the cache. There are four built in concurrency strategies, representing
decreasing levels of strictness in terms of transaction isolation:
* transactional :- Available in a managed environment only. It guarantees full transactional
isolation upto repeatable read, if required.
* read-write :- Maintains read committed isolation, using a timestamping mechanism. It's
available only in non-clustered environments.
* nonstrict-read-write :- Makes no guarantee of consistency between the cache and the database.
If there is a possibility of concurrent access to the same entity , you should configure a sufficiently
short expiry timeout. Otherwise you may read stale data in the catch.
* read-only :- A concurrency strategy suitable for data which never changes. Use it for reference
data only.
What are the various Catching strategies in Hibernate?
Ans:
Catching is such a fundamental concept in object/ralational persistence that you can't understand
the performance, scalability, or transactional semantics of an ORM implementation without first
knowing what kind of catching strategy it uses. There are three types of cache:
* Transaction scope :- Attached to the current unit of work, which may be an actual database
transaction or an application transaction. Every unit of work has its own cache.
* Process scope :- Shared among many unit of work or transaction.
* Cluster scope :- Shared among multiple processes on the same machine or among the multiple
machines in a cluster. It requires some kind of remote process communication to maintain
consistency.
Ques: 18 How will you set the isolation level for database in JDBC connection?
Ans: Every JDBC connection to a database uses the database's default isolation level, usually read
committed or repeatable read. This default can be changed in the database configuration. You may
also set the transaction isolation for JDBC connection using a Hibernate configuration option:
hibernate.connection.isolation = 4
Hibernate will then set this isolation level on every JDBC connection obtained from a connection
pool before starting a transaction. The sensible values for this option are as follows:
* 1-Read uncommitted isolation
* 2-Read committed isolation
* 4-Repeatable read isolation
* 8-Serializable isolation
Explain the Phantom read?
Ans: A transaction executes a query twice, and the second result set includes rows that weren't
visible in the first result set. This situation is caused by another transaction inserting new rows
between the execution of the two queries.
Ques: 21 What is dirty read in transaction isolation issues?
Ans: When one transaction reads changes made by another transaction that hasn't yet been
committed is called dirty read. This is very dangerous, because those changes might later be rolled
back.
55
56
there is one, it uses it, and if there isn't a session in the current context, it creates a new one and
saves it in there.
On the other hand, openSession does not try to store the session, or pull the session from the
current context.
How will you initialize lazy associations in Hibernate?
Ans:
A proxy or collection wrapper is automatically initialized when any of its methods are invoked.
However it is only possible to initialize a proxy or collection wrapper if it's currently associated with
an open session. If you close the session and try to access an uninitialized proxy or collection,
Hibernate throws a runtime exception.
Beacuase of this behaviour, it's sometimes useful to explicitly initialize an object before closing the
session.
We use the static method Hibernate.initialize() for manual initialization:
Session session = session.openSession();
Transaction t = session.beginTransaction();
Category cat = (Category)
session.get(Category.class, id);
Hibernate.initialize(cat.getItems());
t.commit();
session.close();
What is Lazy fetching in Hibernate?
Ans:
When a client request an entity and its association graph of object from the datebase. It isn't
usually necessary to retrieve the dwhole graph.
Lazy fetching lets you decide how much of the object graph is loaded in the first database hit and
which associations should be loaded only when they're first accessed. Lazy fetching is a
foundational concept in object persistence and the first step to attaining accetable performance.
What is outer join fetching in Hibernate?
Ans:
Eager or outer join fetching lets you explicitly specify which associated objects should be loaded
together with the referencing object. Hibernate can then return the associated objects in a single
database request, utilizing an SQL OUTER JOIN.
Even though default eager fetching may be declared in the mapping file, it's more common to
specify the use of this strategy at runtime for a particular HQL or criteria query.
What are the various fetching strategies from the database in Hibernate?
Ans: Hibernate allows you to choose among four fetching strategies for any association, in
association and at runtime:
* Immediate fetching.
* Lazy fetching.
* Eager fatching.
* Batch fetching.
What is Hibernate Query By Example?
Ans: The idea behind Query By Example is that the application supplies an instance of the queried
class with certain property values set. The query returns all persistent instances with matching
property values. QBE isn't a particularly powerful approach, but it can be convenient for some
applications. The following code snippet demonstrates a Hibernate QBE:
User exampleUser = new User();
exampleUser.setFirstName("Max");
Criteria c = session.createCriteria(User.class);
c.add(Example.create(exampleUser));
List r=criteria.list();
What is Hibernate QBC (Query By Criteria)?
Ans: The Hibernate Query By Criteria API lets you build a query by manipulating criteria objects at
runtime. This approach lets you specify constraints dynamically without direct using mainpulations,
but it doesn't lose much of the flexibility or power of HQL.
57
58
59
Ans:
if multiple methods involved in a chain fashion with help of dot operator then it is called as method
chaining.ex PreparedStatement
pstmt=DriverManager.getConnection("url","username","pwd").prepareStatement();
What is the file extension you use for hibernate mapping file?
Ans:
The file extension you use for hibernate mapping file is "filename.hbm.xml".
What are different environments to configure hibernate?
Ans:
There are mainly two types of environments in which the configuration of hibernate application
differs:
* Managed environment : In this kind of environment everything from database connections,
transaction boundaries, security levels and all are defined. An example of this kind of environment
is environment provided by application servers such as JBoss, Weblogic and WebSphere.
* Non-managed environment : This kind of environment provides a basic configuration template.
Tomcat is one of the best examples that provide this kind of environment.
What are the Extension interfaces that are there in hibernate?
Ans:
There are many extension interfaces provided by hibernate:
* ProxyFactory interface
* ConnectionProvider interface
* TransactionFactory interface
* Transaction interface
* TransactionManagementLookup interface
* Cahce interface
* CacheProvider interface
* ClassPersister interface
* IdentifierGenerator interface
* Dialect abstract class.
What are managed associations and hibernate associations?
Ans:
Associations are used to represent relationships between classes. Managed association means that,
if a change is made to one end of the association, it will be reflected at the other end. So when
changes are made to the attributes participating in this association, they will be reflected at the
other end automatically. The developer doesnt have to mange the associations manually. Hibernate
mainly supports two types of associations:
1. One-to-Many
2. Many-to-One
What are the different methods of identifying an object?
Ans:
There are three methods by which an object can be identified:
* Object identity : Objects are identical if they reside in the same memory location in the JVM.
This can be checked by using the = = operator.
* Object equality : Objects are equal if they have the same value, as defined by the equals( )
method. Classes that dont explicitly override this method inherit the implementation defined by
java.lang.Object, which compares object identity.
* Database identity : Objects stored in a relational database are identical if they represent the
same row or, equivalently, share the same table and primary key value.
What are the different types of property and class mappings?
Ans:
The different types of property and class mappings:
* Typical and most common property mapping:
<property name="Name" column="firstName" type="string"/>
Or
<property name="Name" type="string">
<column name="firstName"/>
60
</property>
* Derived properties:
<property name="averageAmount" formula="( select AVG(b.AMOUNT) from TableName a where
a.ITEM_ID = ITEM_ID )" type="big_decimal"/>
* controlling inserts and updates:
<property name="name" column="NAME" type="string" insert="false" update="false"/>
What are POJOs?
Ans: POJO stands for plain old java objects. These are just basic JavaBeans that have defined
setter and getter methods for all the properties that are there in that bean. Besides they can also
have some business logic related to that property. Hibernate applications works efficiently with
POJOs rather then simple java classes.
Where should SessionFactory be placed so that it can be easily accessed?
Ans:
If the SessionFactory is placed in JNDI then it can be easily accessed and shared between different
threads and various components that are hibernate aware. You can set the SessionFactory to a
JNDI by configuring a property hibernate.session_factory_name in the hibernate.properties file.
Ques: 56 What is attribute oriented programming?
Ans:
XDoclet is an open source code generation engine. It enables Attribute-Oriented Programming for
java. In short, this means that you can add more significance to your code by adding meta data
(attributes) to your java sources. This is done in special JavaDoc tags.
XDoclet lets you apply Continuous Integration in component-oriented development. Developers
should concentrate their editing work on only one Java source file per component.
How will you map the metadata in configuration file in Hibernate?
Ans:
In Hibernate 2.x, mapping metadata is most of the time declared in XML text files. Another option
is XDoclet, utilizing Javadoc source code annotations and a preprocessor at compile time. The same
kind of annotation support is now available in the standard JDK.
Hibernate mapping elements accept the node attribute. This let's you specify the name of an XML
attribute or element that holds the property or entity data. The format of the node attribute must
be one of the following:
* element-name - map to the named XML element
* attribute-name - map to the named XML attribute
* .(dot) - map to the parent element
* element-name/attribute-name - map to the named attribute of the named element.
What are the Transparent and Automated persistence in Hibernate?
Ans:
Hibernate provides automatic and transparent object/relational mapping making it a snap to work
with SQL databases in Java applications.
Application server's CMP engine implements automated pesistence. It takes care of the tedious
details of JDBC ResultSet and PreparedStatement handling.
The ability to directly manipulate data stored in a relational database using an object programming
language is called transparent persistence. With transparent persistence, the manipulation and
traversal of persistent objects is performed directly by the object programming language in the
same manner as in-memory, non-persistent objects.
what is CaveatEmptor application in Hibernate?
Ans:
CaveatEmptor's primary purpose is to educate on how to build a persistence service/layer with
Hibernate. CaveatEmptor is an online auction application with business objects such as Item, User,
and Bid. The domain model covers various kinds of entities, entity associations and collections. The
Caveat Emptor is a simple book auction application built with XUI 3.1. It shows how to use the
Hibernate POJO support in a two tiered scenario, where the Hibernate serves as a peristence layer
(it is being used to directly connect to the database).
What is Java Management Extension (JMX) in Hibernate?
61
Ans:
JMX is standard API for managing the Java application and components. JMX is a management
technology that can be used to manage any kind of resource. The JMX technology provides the
tools for building distributed, Web-based, modular and dynamic solutions for managing and
monitoring devices, applications, and service-driven networks.
There have been various management technologies in the market for Network and Telephonic
Domains. Though JMX is not specifically oriented towards any domain, it can be used to manage
and monitor resources in any domain. The major levels defined in JMX are:
* Instrumental Level
* Agent Level
* Remote Management Level
What is JNDI-bound SessionFactory in Hibernate?
Ans:
A JNDI bound Hibernate SessionFactory can simplify the lookup of the factory and the creation of
new Sessions. If you wish to have the SessionFactory bound to a JNDI namespace, specify a name
(eg. java:comp/env/hibernate/SessionFactory) using the property hibernate.session_factory_name.
If this property is omitted, the SessionFactory will not be bound to JNDI. When binding the
SessionFactory to JNDI, Hibernate will use the values of hibernate.jndi.url, hibernate.jndi.class to
instantiate an initial context. If they are not specified, the default InitialContext will be used.
Ques: 62 What are the various advanced configuration techniques in Hibernate?
Ans:
Advanced configuration techniques in Hibernate:
* Using XML-based configuration :
<hibernate-configuration>
<session-factory>
<!-- properties -->
<property name= "dialect">org.hibernate.dialect.MySQL5Dialect</property>
<property name="connection.datasource">java:comp/env/jdbc/yourDatabase</property>
<property name="show_sql">true</property>
<property name="use_outer_join">true</property>
<property
name="transaction.factory_class">org.hibernate.transaction.JDBCTransactionFactory</property>
<property name="current_session_context_class">thread</property>
<!-- mappings -->
<mapping class="com.MyProject.model.User" />
</session-factory>
</hibernate-configuration>
* JNDI-bound SessionFactory
* Logging
* Java Management Extensions (JMX)
Whats the difference between load() and get()?
Ans:
Both load() and get() methods used to find out the object in cache or database. Use get() method if
you are not sure that the object exists. The get() method will return null if the unique id is not
found in the database. The get() will hit the database immediately.
Use the load() method if you are sure that the object exists. The load() method will throw an
exception if the unique id is not found in the database. The load() just returns a proxy by default
and database wont be hit until the proxy is first invoked.
Explain about mapping description file?
Ans:
Hibernate can be configured with two types of files out of which hibernate.cfg.xml is the mapping
description file in which Hibernate uses to configure its functions. This mapping file has an
extension *.hbm which instructs mapping between Java class and database tables. The usage of
mapping description file rests entirely upon the business entity.
62
63
database to cache the query plan. There is no reason to avoid the use of generated SQL in modern
applications.
How can we get access to O/R mapping information such as table and column names at
runtime?
Ans:
This information is available via the Configuration object. For example, entity mappings may be
obtained using Configuration.getClassMapping(). It is even possible to manipulate this metamodel
at runtime and then build a new SessionFactory.
Does Hibernate implement its functionality using a minimal number of database queries?
Ans:
Hibernate can make certain optimizations implement its functionality using a minimal number of
database queries:
* Caching objects
* Executing SQL statement when needed.
* Never updating unmodified objects.
* Efficient Collection Handling.
* Updating only the modified columns.
* Outer join fetching.
* Lazy collection initialization.
* Lazy object initialization.
Ques: 77 How does Hibernate distinguish between transient (i.e. newly instantiated) and
detached objects?
Ans:
The EmptyInterceptor class provides the isTransient() method to check whether the object is
transient or deteched. Method signature:
java.lang.Boolean isTransient(java.lang.Object obj)
What are the benefits of detached objects?
Ans:
Detached objects can be passed across layers all the way up to the presentation layer without
having to use any DTOs(Data Transfer Objects). You can later on re-attach the detached objects to
another session.
Explain the various object states in Hibernate?
Ans:
Hibernate defines and supports the following object states:
* Transient :- an object is transient if it has just been instantiated using the new operator, and it
is not associated with a Hibernate Session. It has no persistent representation in the database and
no identifier value has been assigned.
* Persistent :- a persistent instance has a representation in the database and an identifier value.
It might just have been saved or loaded, however, it is by definition in the scope of a Session.
* Detached :- a detached instance is an object that has been persistent, but its Session has been
closed. The reference to the object is still valid, of course, and the detached instance might even be
modified in this state. A detached instance can be reattached to a new Session at a later point in
time, making it persistent again.
What are the types of inheritence models in Hibernate?
Ans:
There are three types of inheritance mapping in hibernate:
1. Table per concrete class with unions.
2. Table per class hierarchy.
3. Table per subclass.
What is the general flow of Hibernate communication with RDBMS?
Ans:
The general flow of Hibernate communication with RDBMS is:
* Load the Hibernate configuration file and create configuration object. It will automatically load
all hbm mapping files.
* Create session factory from configuration object.
64
65
Object proxies can be defined in one of two ways. First, you can add a proxy attribute to the class
element. You can either specify a different class or use the persistent class as the proxy.
For example:
<class name="Location"
proxy="com.ch01.Location">
</class>
The second method is to use the lazy attribute. Setting lazy="true"is a shorthand way of defining
the persistent class as the proxy. Let's assume the Location class is defined as lazy:
<class name="Location"lazy="true"...>...</class>
what is lazy initialisation in hibernate?
Ans:
Hibernate supports the feature of lazy initilasation for both entities and collections. What this
actually means is, the Hibernate engine loads only those objects that we are querying for and
doesnt try to fetch other entities(that are associated with the entity we are querying) or collections.
Hibernate loads collection elements only when actually you ask for them by saying lazy=true or
lazy=false.
Example:
<set name="Child" lazy="false" inverse="true">
<key column="COL"/>
<one-to-many class="Parent"/>
</set>
How to call stored procedure in mysql through hibernate?
Ans:
If your stored procedure is returning a value you can directly use <sql-query>, otherwise you need
to use jdbc connection to call the native sql procedure.
Example:
Session session = getHibernateTemplate().getSessionFactory().openSession();
/*if you are not using session factory, you can use ur own method to get session.*/
Connection conn = session.connection();
String sqlQuery = "call VersionUpdateProcedure()";
CallableStatement cs = conn.prepareCall(sqlQuery);
cs.execute();
conn.close();
session.close();
What are the most common methods of Hibernate configuration?
Ans:
The two most common methods of Hibernate configuration are:
* Programmatic configuration
* XML configuration (hibernate.cfg.xml)
What Does Hibernate Simplify?
Ans:
Hibernate simplifies :
* Saving and retrieving your domain objects
* Making database column and table name changes
* Centralizing pre save and post retrieve logic
* Complex joins for retrieving related items
* Schema creation from object model
What is ORM? What does ORM consists of?
Ans:
ORM stands for object/relational mapping. ORM is the automated persistence of objects in a Java
application to the tables in a relational database.
An ORM solution consists of the followig four pieces:
* API for performing basic CRUD operations
* API to express ries refering to classes
66
67
68
69
I have a many-to-many association between two tables, but the association table has
some extra columns (apart from the foreign keys). What kind of mapping should I
use?
Use a composite-element to model the association table. For example, given the following
association table:
create table relationship (
fk_of_foo bigint not null,
fk_of_bar bigint not null,
multiplicity smallint,
created date )
you could use this collection mapping (inside the mapping for class Foo):
<set name="relationship">
<key column="fk_of_foo"/>
<composite-element class="Relationship">
<property name="multiplicity" type="short" not-null="true"/>
<property name="created" type="date" not-null="true"/>
<many-to-one name="bar" class="Bar" not-null="true"/>
</composite-element>
</set>
You may also use an <idbag> with a surrogate key column for the collection table. This would allow
you to have nullable columns.
An alternative approach is to simply map the association table as a normal entity class with two
bidirectional one-to-many associations.
In an MVC application, how can we ensure that all proxies and lazy collections will be
initialized when the view tries to access them?
One possible approach is to leave the session open (and transaction uncommitted) when forwarding
to the view. The session/transaction would be closed/committed after the view is rendered in, for
example, a servlet filter (another example would by to use the ModelLifetime.discard() callback in
Maverick). One difficulty with this approach is making sure the session/transaction is closed/rolled
back if an exception occurs rendering the view.
Another approach is to simply force initialization of all needed objects using Hibernate.initialize().
This is often more straightforward than it sounds.
How can I bind a dynamic list of values into an in query expression?
70
71
I have a collection with second-level cache enabled, and Hibernate retrieves the
collection elements one at a time with a SQL query per element!
Enable second-level cache for the associated entity class. Don't cache collections of uncached entity
types.
How can I insert XML data into Oracle using the xmltype() function?
Specify custom SQL INSERT (and UPDATE) statements using <sql-insert> and <sql-update> in
Hibernate3, or using a custom persister in Hibernate 2.1.
You will also need to write a UserType to perform binding to/from the PreparedStatement.
How can I execute arbitrary SQL using Hibernate?
PreparedStatement ps = session.connection().prepareStatement(sqlString);
Or, if you wish to retrieve managed entity objects, use session.createSQLQuery().
Or, in Hibernate3, override generated SQL using <sql-insert>, <sql-update>, <sqldelete> and <loader> in the mapping document.
I want to call an SQL function from HQL, but the HQL parser does not recognize it!
Subclass your Dialect, and call registerFunction() from the constructor.
HQL: The Hibernate Query Language The Hibernate Query Language is executed using
session.createQuery(). This tutorial includes from clause,Associations and joins, Aggregate
functions,The order by clause,The group by clause,Subqueries.
The from clause
from Employee // Employee is class name mapped to EMPLOYEE
TABLE
or
from Employee as e
or
from Employee e where e.empId = 3;
List empList = session.createQuery("from Employee").list();
Associations and joins
from Employee e where e.scopeModFlag = 1 and pc.isDeleted != 1
List empList = session.createQuery("from Employee e where
e.scopeModFlag = 1 and pc.isDeleted != 1").list();
Aggregate functions
select avg(cat.weight), sum(cat.weight), max(cat.weight), count(cat)
from Cat cat ScrollableResults rs = session.createQuery("select
avg(cat.weight), sum(cat.weight), max(cat.weight), count(cat) from
Cat cat").scroll();
if(rs.next()){
System.out.println(rs.get(0));
System.out.println(rs.get(1));
System.out.println(rs.get(2));
System.out.println(rs.get(3));
}
The order by clause
from Employee e order by e.name desc
List empList = session.createQuery("from Employee e order by
e.name desc").list();
asc or desc indicate ascending or descending order respectively.
The group by clause
select e.dept, sum(e.salary), count(e) Employee e group by cat.dept
Subqueries
from Employee as e
where e.name = some (
72
73
74
session.createCriteria(Employee.class).add( Restrictions.eq("age",
new Integer(24) ) ).list();
NotEqual (ne)
NotEqual (ne) : Is used to check not equal in the query.
// SELECT * FROM EMPLOYEE WHERE AGE !=24; ----SQL COMMAND
// Not Equal in hibernate criteria criteria query for above query is :
List empList =
session.createCriteria(Employee.class).add( Restrictions.ne("age",
new Integer(24) ) ).list();
Less than (lt)
Less than (lt) : Is used to check less than in the query.
// SELECT * FROM EMPLOYEE WHERE AGE < 24; ----SQL COMMAND
// Not Equal in hibernate criteria criteria query for above query is :
List empList =
session.createCriteria(Employee.class).add( Restrictions.lt("age", new
Integer(24) ) ).list();
Less than or equal(le)
Less than or equal(le) : Is used to check less than or equal in the query.
// SELECT * FROM EMPLOYEE WHERE AGE <= 24; ----SQL COMMAND
// Not Equal in hibernate criteria criteria query for above query is :
List empList =
session.createCriteria(Employee.class).add( Restrictions.le("age", new
Integer(24) ) ).list();
Greater than (gt)
Greater than (gt) : Is used to check greater than in the query.
// SELECT * FROM EMPLOYEE WHERE AGE > 24; ----SQL COMMAND
// Not Equal in hibernate criteria criteria query for above query is :
List empList =
session.createCriteria(Employee.class).add( Restrictions.gt("age",
new Integer(24) ) ).list();
Greater than or equal (gt)
Greater than or equal (gt) : Is used to check greater than or equal in the query.
// SELECT * FROM EMPLOYEE WHERE AGE >= 24; ----SQL COMMAND
// Not Equal in hibernate criteria criteria query for above query is :
List empList =
session.createCriteria(Employee.class).add( Restrictions.ge("age",
new Integer(24) ) ).list();
Ordering the results
// SELECT * FROM EMPLOYEE WHERE AGE=24 ORDER BY NAME
DESC; ----SQL COMMAND
criteria query for above query is :
List empList = session.createCriteria(Employee.class).
add( Restrictions.eq("age", new
Integer(24) ) ).addOrder( Order.desc("name") ).list();
Criteria Queries: And OR conditions The interface org.hibernate.Criteria represents a query
against a particular persistent class. The Session is a factory for Criteria instances. In this section it
show how to create TABLE and POJO Java class and Mapping with the Query.
Create TABLE EMPLOYEE.
Create TABLE EMPLOYEE(
id number;
75
name varchar;
age number;
);
Create Employee.java bean class.
Hibernate uses the Plain Old Java Objects (POJOs) classes to map to the database table (Emp.java
to EMPLOYEE TABLE). We can configure the variables to map to the database column.
public class Employee {
private long id;
private String name;
private int age;
public long getId() {
return id;
}
private void setId(long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
private void setAge(int age) {
this.age = age;
}
}
76
This method returns the disjuction of two expressions. Any given condition is 'true' then it executes
the query. In this tutorial, "or" is used
// SELECT * FROM EMPLOYEE WHERE AGE=24 OR AGE=28; ----SQL
COMMAND
criteria query for above query is :
List empList = session.createCriteria(Employee.class)
.add(Expression.or(
Expression.eq("age", new Integer(24) ) ),
Expression.eq("age", new Integer(28) ) ))
.list();
Prevent concurrent update in Hibernate
This tutorial resolve the issue of User think time : ( one user edit the record for update and thinking
and changing values , same time other user edit the same record and update. then first user
update and 2nd user's data is lost.)
You can say this is version checking in Hibernate or perevent slate object updatation in
Hibernate. 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 lost.
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).
Below steps to prevent concurrent update in Hibernate.
Step 1. Declare a variable "versionId" in your bean Class with setter and getter method.
public class Writer {
private int id;
private String name;
private long versionId; public void setId(int i) {
id = i;
}
public int getId() {
return id;
}
public void setName(String n) {
name = n;
}
public String getName() {
return name;
}
public long getVersionId() {
return versionId;
}
public void setVersionId(long versionId) {
this.versionId = versionId;
}
}
Step 2. Add Extra coulmn name "version" in the WRITER TABLE.
create table WRITER (
ID number, //PRIMARY KEY
NAME varchar,
version number
);
77
78
Hibernate Type
SQL Type
number
char
character
java.math.BigDecimal
big_decimal
float, double
float, double
boolean
java.lang.string
java.util.Date
NUMERIC, NUMBER
float, double
java.lang.Boolean, boolean
char
boolean, int
string
varchar, varchar2
text
CLOB, TEXT
79
java.util.Calendar
java.util.Locale
java.util.TimeZone
java.util Currency
calendar, calendar_date
locale
TIMESTAMP, DATE
varchar,varchar2
timezone
varchar, varchar2
Currency
varchar, varchar2
java.sql.Clob
clob
java.sql.Blob
blob
BLOB
Java object
serializable
binary field
byte array
binary
binary field
java.lang.Class
CLOB
class
varchar, varchar2
1. What is Hibernate?
Hibernate is a pure Java object-relational mapping (ORM) and persistence framework that allows
you to map plain old Java objects to relational database tables using (XML) configuration files.Its
purpose is to relieve the developer from a significant amount of relational data persistence-related
programming tasks.
2. What is ORM?
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.
3. What does an ORM solution comprises of?
It should have an API for performing basic CRUD (Create, Read, Update, Delete) operations on
objects of persistent classes Should have a language or an API for specifying queries that refer to
the classes and the properties of classes An ability for specifying mapping metadata It should have
a technique for ORM implementation to interact with transactional objects to perform dirty
checking, lazy association fetching, and other optimization functions
4. What are the different levels of ORM quality?
There are four levels defined for ORM quality.
Pure relational
object mapping
Medium object mapping
Full object mapping
5. What is a pure relational ORM?
The entire application, including the user interface, is designed around the relational model and
SQL-based relational operations.
6. Why do you need ORM tools like hibernate?
The main advantage of ORM like hibernate is that it shields developers from messy SQL. Apart from
this, ORM provides following benefits:
1. Improved productivity
High-level object-oriented API
Less Java code to write
No SQL to write
2. Improved performance
Sophisticated caching
Eager loading
80
3. Improved maintainability
A lot less code to write
4. Improved portability
ORM framework generates database-specific SQL for you
7. What is a meant by light object mapping?
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.
8. What is a meant by medium object mapping?
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.
9. What is meant by full object mapping?
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.
10. What are the benefits of ORM and Hibernate?
There are many benefits from these. Out of which the following are the most important one.
Productivity : Hibernate reduces the burden of developer by providing much of the functionality and
let the developer to concentrate on business logic.
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.
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.
Vendor independence : Irrespective of the different types of databases that are there, hibernate
provides a much easier way to develop a cross platform application.
11. What the Core interfaces are of hibernate framework?
There are many benefits from these. Out of which the following are the most important one.
Session Interface : This is the primary interface used by hibernate applications. The instances of
this interface are lightweight and are inexpensive to create and destroy. Hibernate sessions are not
thread safe.
SessionFactory Interface : This is a factory that delivers the session objects to hibernate
application. Generally there will be a single SessionFactory for the whole application and it will be
shared among all the application threads.
Configuration Interface : This interface is used to configure and bootstrap hibernate. The instance
of this interface is used by the application in order to specify the location of hibernate specific
mapping documents.
Transaction Interface : This is an optional interface but the above three interfaces are mandatory in
each and every application. This interface abstracts the code from any kind of transaction
implementations such as JDBC transaction, JTA transaction.
Query and Criteria Interface : This interface allows the user to perform queries and also control the
flow of the query execution.
12. What are Callback interfaces?
These interfaces are used in the application to receive a notification when some object events
occur. Like when an object is loaded, saved or deleted. There is no need to implement callbacks in
hibernate applications, but theyre useful for implementing certain kinds of generic functionality.
81
82
Ans:
The ANSI SQL standard defines the standart transaction isolation levels in terms of which of these
phenomenon are permissible:
* Last update
* Dirty read
* Unrepeatable read
* Second lost updates problem
* Phantom read
Ques: 23 Explain Hibernate Transaction API?
Ans:
The Transaction interface provides methods for declaring the boundaries of a database transaction.
Example:
Session s = sessions.openSession();
Transaction t = null;
try{
t = s.beginTransaction();
concludeAuction();
t.commit();
} catch(Exception e) {
if(t!=null) {
try{
t.rollback();
} catch (HibernateException h) {
// log h and rethrow e
}
}
throw e;
}finally {
try{
s.close();
} catch (HibernateException h) {
throw h;
}
}
Ques: 24 What auto commint mode should you use in JDBC connection in Hibernate?
Ans:
A magical setting that is often a source of confusion is the JDBC connection's auto commit mode. If
a database connection is in auto commit mode, the database transaction will be committed
immediately after each SQL statement, and a new transaction will be started. This can be useful for
ad hoc database queries and ad hoc data updates.
What is the difference between JDBC and JTA transactions in Hibernate?
Ans:
In a non-managed environment, the JDBC API is used to mark transaction boundaries. You begin a
transaction by calling setAutoCommit(false) on a JDBC connection and end it by calling commit().
You may, at any time, force an intermediate rollback by calling rollback().
In a system that stores data in multiple databases, you can't achieve atomaticity using JDBC alone.
You require a transaction manager with support for distributed transactions (two-phase commit).
You communicate with the transaction manager using the JTA (Java Transaction API).
In a managed environment, JTA is used only for distributed transaction, but also for declarative
container managed transaction (CMT).
Difference between getCurrentSession() and openSession() in Hibernate ?
Ans:
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 commits. You can call
getCurrentSession() as often and anywhere you want as long as the transaction runs. The
getCurrentSession() method looks at the current context to see if a session is stored in there. If
there is one, it uses it, and if there isn't a session in the current context, it creates a new one and
saves it in there.
83
On the other hand, openSession does not try to store the session, or pull the session from the
current context.
How will you initialize lazy associations in Hibernate?
Ans:
A proxy or collection wrapper is automatically initialized when any of its methods are invoked.
However it is only possible to initialize a proxy or collection wrapper if it's currently associated with
an open session. If you close the session and try to access an uninitialized proxy or collection,
Hibernate throws a runtime exception.
Beacuase of this behaviour, it's sometimes useful to explicitly initialize an object before closing the
session.
We use the static method Hibernate.initialize() for manual initialization:
Session session = session.openSession();
Transaction t = session.beginTransaction();
Category cat = (Category)
session.get(Category.class, id);
Hibernate.initialize(cat.getItems());
t.commit();
session.close();
What is Lazy fetching in Hibernate?
Ans:
When a client request an entity and its association graph of object from the datebase. It isn't
usually necessary to retrieve the dwhole graph.
Lazy fetching lets you decide how much of the object graph is loaded in the first database hit and
which associations should be loaded only when they're first accessed. Lazy fetching is a
foundational concept in object persistence and the first step to attaining accetable performance.
What is outer join fetching in Hibernate?
Ans:
Eager or outer join fetching lets you explicitly specify which associated objects should be loaded
together with the referencing object. Hibernate can then return the associated objects in a single
database request, utilizing an SQL OUTER JOIN.
Even though default eager fetching may be declared in the mapping file, it's more common to
specify the use of this strategy at runtime for a particular HQL or criteria query.
What are the various fetching strategies from the database in Hibernate?
Ans:
Hibernate allows you to choose among four fetching strategies for any association, in association
and at runtime:
* Immediate fetching.
* Lazy fetching.
* Eager fatching.
* Batch fetching.
What is Hibernate Query By Example?
Ans:
The idea behind Query By Example is that the application supplies an instance of the queried class
with certain property values set. The query returns all persistent instances with matching property
values. QBE isn't a particularly powerful approach, but it can be convenient for some applications.
The following code snippet demonstrates a Hibernate QBE:
User exampleUser = new User();
exampleUser.setFirstName("Max");
Criteria c = session.createCriteria(User.class);
c.add(Example.create(exampleUser));
List r=criteria.list();
84
What are the various ways to fetch objects from database in Hibernate?
Ans:
Hibernate provides the following ways to get objects out of the database:
* Navigating the object graph, starting from an already loaded object, by accessing the associated
objects through property accessor methods.
* Retrieving by Identifier.
* Using the Hibernate Query Language (HQL).
* Using the Hibernate Criteria API.
* Using native SQL Queries.
What is the difference between beans and Hibernate?
Ans:
Hibernate uses POJO classes for handling persistence, these classes need to adhere normal bean
writing. Beans are at form (view) level and Hibernate are at database level.
JavaBeans are simple reusable component whereas hibernate are supports for the JavaBean object
persistency.
How will you create a primary key using Hibernate?
Ans:
The id field in hbm.xml file is used to specify the primary key in database. We can also use
generator to specify the way primary key is generated to the database.
For example
85
86
87
88
89
90
key value by selecting a value from a database trigger. The generator type you choose determines
its behavior based on the underlying database.
You've used the native generator class in mapping definitions. native generators provide portability
for mapping documents since the framework can determine the generator method supported by the
database. Generators using the native class will use identity or sequence columns depending on
available database support. If neither method is supported, the native generator falls back to a
high/low generator method to create unique primary key values. Databases supporting identity
columns include Sybase, MySQL, Microsoft SQL Server, and IBM DB2. Oracle, PostgreSQL, and SAP
DB support sequence columns.
The native generator returns a short, integer, or long value. You've set the type attribute to long,
and the id property in the Event object has a type of java.lang.Long. The value of the type attribute
and the property type in the object must be the same.
The different types of Id generators supported by hibernate are:
1. increment: It generates identifiers of type long, short or int that are unique only when no
other process is inserting data into the same table. It should not the used in the clustered
environment.
2. identity: It supports identity columns in DB2, MySQL, MS SQL Server, Sybase and
HypersonicSQL. The returned identifier is of type long, short or int.
3. sequence: The sequence generator uses a sequence in DB2, PostgreSQL, Oracle, SAP DB,
McKoi or a generator in Interbase. The returned identifier is of type long, short or int
4. hilo: The hilo generator uses a hi/lo algorithm to efficiently generate identifiers of type long,
short or int, given a table and column (by default hibernate_unique_key and next_hi
respectively) as a source of hi values. The hi/lo algorithm generates identifiers that are
unique only for a particular database. Do not use this generator with connections enlisted
with JTA or with a user-supplied connection.
5. seqhilo: The seqhilo generator uses a hi/lo algorithm to efficiently generate identifiers of
type long, short or int, given a named database sequence.
6. uuid: The uuid generator uses a 128-bit UUID algorithm to generate identifiers of type
string, unique within a network (the IP address is used). The UUID is encoded as a string of
hexadecimal digits of length 32.
7. guid: It uses a database-generated GUID string on MS SQL Server and MySQL.
8. native: It picks identity, sequence or hilo depending upon the capabilities of the underlying
database.
9. assigned: lets the application to assign an identifier to the object before save() is called.
This is the default strategy if no <generator> element is specified.
10. select: retrieves a primary key assigned by a database trigger by selecting the row by some
unique key and retrieving the primary key value.
11. foreign: uses the identifier of another associated object. Usually used in conjunction with a
<one-to-one> primary key association.
The unsaved-value attribute describes the value of the id property for transient instances of this
class. The unsaved-value attribute affects how objects are stored. We'll discuss the impact of this
attribute later in the article.
Properties
Property elements for the Event object are similar to the id element:
<property name="name"type="string"length="100"/>
<property name="startDate"column="start_date"type="date"/>
<property name="duration"type="integer"/>
Each property element corresponds to a property in the Event object. The name attribute contains
the property name, whereas the type attribute specifies the property object type. The column used
to store the property value defaults to the property name. The column attribute overrides this
default behavior, as shown in the startDate property.
If the type attribute is omitted, Hibernate determines the type using runtime reflection. In certain
cases, you must provide the property type, since reflection may not be able to determine the
desired type (such as differentiating between the Hibernate DATE and TIMESTAMP types). Valid
property types include the Hibernate basic types, such as integer, string, and timestamp, as well as
the corresponding Java objects and primitives. However, you aren't limited to basic data types.
The property element may also contain the name of a serializable Java class or a user-defined type.
91
92
This also applies to child collections, but you can only fetch one collection using a join per
persistent object. Additional collections must be fetched using the SELECT strategy.
If you're using Hibernate 2, the fetch attribute is not available. Instead, you must use the outerjoin attribute for many-to-one associations. (There is no support for retrieving collections using a
SELECT in Hibernate 2.) The outer-join attribute takes either a true or false value.
Building the SessionFactory
Hibernate's SessionFactory interface provides instances of the Session class, which represent
connections to the database. Instances of SessionFactory are thread-safe and typically shared
throughout an application. Session instances, on the other hand, aren't thread-safe and should only
be used for a single transaction or unit of work in an application.
Configuring the SessionFactory
The Configuration class kicks off the runtime portion of Hibernate. It's used to load the mapping
files and create a SessionFactory for those mapping files. Once these two functions are complete,
the Configuration class can be discarded. Creating a Configuration and SessionFactory instance is
simple, but you have some options. There are three ways to create and initialize a Configuration
object.
This first snippet loads the properties and mapping files defined in the hibernate.cfg.xml file and
creates the SessionFactory:
Configuration cfg =new Configuration();
SessionFactory factory =cfg.configure().buildSessionFactory();
The configure()method tells Hibernate to load the hibernate.cfg.xml file. Without that, only
hibernate.properties would be loaded from the classpath. The Configuration class can also load
mapping documents programmatically:
Configuration cfg =new Configuration();
cfg.addFile("com/manning/hq/ch03/Event.hbm.xml");
Another alternative is to have Hibernate load the mapping document based on the persistent class.
This has the advantage of eliminating hard-coded filenames in the source code. For instance, the
following code causes Hibernate to look for a file named com/manning/hq/ Event.hbm.xml in the
classpath and load the associated class:
Configuration cfg =new Configuration();
cfg.addClass(com.manning.hq.ch03.Event.class);
Since applications can have tens or hundreds of mapping definitions, listing each definition can
quickly become cumbersome. To get around this, the hibernate.cfg.xml file supports adding all
mapping files in a JAR file. Suppose your build process creates a JAR file named application.jar,
which contains all the classes and mapping definitions required. You then update the
hibernate.cfg.xml file:
<mapping jar="application.jar"/>
Of course, you can also do this programmatically with the Configuration class:
Configuration.addJar(new java.io.File("application.jar"));
Keep in mind that the JAR file must be in the application classpath. If you're deploying a web
application archive (WAR) file, your application JAR file should be in the /WEB-INF/lib directory in
the WAR file.
The four methods used to specify mapping definitions to the Hibernate runtime can be combined,
depending the requirements for your project. However, once you create the SessionFactory from
the Configuration instance, any additional mapping files added to the Configuration instance won't
be reflected in the SessionFactory . This means you can't add new persistent classes dynamically.
You can use the SessionFactory instance to create Session instances:
Session session =factory.openSession();
Instances of the Session class represent the primary interface to the Hibernate framework. They let
you persist objects, query persistent objects, and make persistent objects transient. Let's look at
persisting objects with Hibernate.
Persisting objects
Persisting a transient object with Hibernate is as simple as saving it with the Session instance:
93
94
This query is a little more interesting since we're querying on a property of the Event class:
Query query =session.createQuery("from Event where name ="+
"'Opening Presentation'");
List events =query.list();
We've hardcoded the name value in the query, which isn't optimal. Let's rewrite it:
Query query =session.createQuery("from Event where name =?",
"Opening Presentation");
query.setParameter(0,"Opening Presentation",Hibernate.STRING);
List events =query.list();
The question mark in the query string represents the variable, which is similar to the JDBC
PreparedStatement interface. The second method parameter is the value bound to the variable, and
the third parameter tells Hibernate the type of the value. (The Hibernate class provides constants
for the built-in types, such as STRING , INTEGER , and LONG , so they can be referenced
programmatically.)
One topic we haven't touched on yet is the cache maintained by the Session. The Session cache
tends to cause problems for developers new to Hibernate, so we'll talk about it next.
The Session cache
One easy way to improve performance within the Hibernate service, as well as your applications, is
to cache objects. By caching objects in memory, Hibernate avoids the overhead of retrieving them
from the database each time. Other than saving overhead when retrieving objects, the Session
cache also impacts saving and updating objects. Let's look at a short code listing:
Session session =factory.openSession();
Event e =(Event)session.load(Event.class,myEventId);
e.setName("New Event Name");
session.saveOrUpdate(e);
//later,with the same Session instance
Event e =(Event)session.load(Event.class,myEventId);
e.setDuration(180);
session.saveOrUpdate(e);
session.flush();
This code first retrieves an Event instance, which the Session caches internally. It then does the
following: updates the Event name, saves or updates the Event instance, retrieves the same Event
instance (which is stored in the Session cache), updates the duration of the Event,and saves or
updates the Event instance. Finally, you flush the Session.
All the updates made to the Event instance are combined into a single update when you flush the
Session. This is made possible in part by the Session cache.
The Session interface supports a simple instance cache for each object that is loaded or saved
during the lifetime of a given Session. Each object placed into the cache is keyed on the class type,
such as The Session cache com.manning.hq.ch03.Event, and the primary key value. However, this
cache presents some interesting problems for unwary developers.
A common problem new developers run into is associating two instances of the same object with
the same Session instance, resulting in a NonUniqueObjectException. The following code generates
this exception:
Session session =factory.openSession();
Event firstEvent =(Event)session.load(Event.class,myEventId);
//...perform some operation on firstEvent
Event secondEvent =new Event();
secondEvent.setId(myEventId);
session.save(secondEvent);
This code opens the Session instance, loads an Event instance with a given ID, creates a second
Event instance with the same ID, and then attempts to save the second Event instance, resulting in
the Non-UniqueObjectException.
Any time an object passes through the Session instance, it's added to the Sessions cache. By
passes through, we're referring to saving or retrieving the object to and from the database. To see
whether an object is contained in the cache, call the Session.contains()method. Objects can be
evicted from the cache by calling the Session.evict() method. Let's revisit the previous code, this
time evicting the first Event instance:
95
If your preferred connection pool API isn't currently supported by Hibernate, you can add support for it
by implementing the org.hibernate.connection.ConnectionProvider interface. Implementing the interface
is straightforward.
Connection pooling services
Pooling Service
C3PO
Provider Class
Apache DBCP
Configuration Prefix
Proxool
96
c3p0
Dbcp
proxool
There isn't much to using a connection pool, since Hibernate does most of the work behind the
scenes. The next configuration topic well look at deals with transaction management with the
Hibernate Transaction API.
Transactions
Transactions group many operations into a single unit of work. If any operation in the batch fails, all
of the previous operations are rolled back, and the unit of work stops. Hibernate can run in many
different environments supporting various notions of transactions. Standalone applications and
some application servers only support simple JDBC transactions, whereas others support the Java
Transaction API (JTA).
Hibernate needs a way to abstract the various transaction strategies from the environment.
Hibernate has its own Transaction class that is accessible from the Session interface, demonstrated
here:
Session session =factory.openSession();
Transaction tx =session.beginTransaction();
Event event =new Event();
//...populate the Event instance
session.saveOrUpdate(event);
tx.commit();
In this example, factory is an initialized SessionFactory instance. This code creates an instance of
the org.hibernate.Transaction class and then commits the Transaction instance.
Notice that you don't need to call session.flush(). Committing a transaction automatically flushes
the Session object. The Event instance is persisted to the database when the transaction is
committed. The transaction strategy you use (JDBC or JTA) doesn't matter to the application codeit's set in the Hibernate configuration file.
The transaction.factory_class property defines the transaction strategy that Hibernate uses. The
default setting is to use JDBC transactions since they're the most common. To use JTA transactions,
you need to set the following properties in hibernate.cfg.xml:
<property name="transaction.factory_class">
org.hibernate.transaction.JTATransactionFactory
</property>
<property name="jta.UserTransaction">
java:comp/UserTransaction
</property>
The transaction.factory_class property tells Hibernate that you'll be using JTA transactions.
Currently, the only other option to JTA is JBDC transactions, which is the default. JTA transactions
are retrieved from a JNDI URI, which is specified using the jta.User-Transaction property. If you
don't know the URI for your specific application server, the default value is
java:comp/UserTransaction.
There is some confusion about another property related to JTA transactions:
transaction.manager_lookup_class. You only need to specify the manager lookup class when you're
using a transactional cache. (We discuss caches in the next sectiondon't worry.) However, if you
don't define the jta.UserTransaction property and transaction.manager_lookup_class is defined, the
user transaction name in the lookup factory class is used. If neither of the properties are used,
Hibernate falls back to java:comp/UserTransaction.
What's the benefit of using JTA transactions? JTA transactions are useful if you have multiple
transactional resources, such as a database and a message queue. JTA allows you to treat the
disparate transactions as a single transaction. Combining multiple transactions also applies within
Hibernate. If you attempt to create multiple transactions from the same Session instance, all of the
operations are batched into the first transaction. Let's look at an example that includes two
transactions:
Transaction tx0 =session.beginTransaction();
Event event =new Event();
//...populate the event instance
session.saveOrUpdate(event);
Transaction tx1 =session.beginTransaction();
Location location =new Location();
//...populate the Location instance
97
session.saveOrUpdate(location);
tx0.commit();
tx1.commit();
This example begins by creating a new transaction. The second use of
session.beginTransaction()just returns the first transaction instance.
session.saveOrUpdate(location)commits the first transaction, and tx0.commit()recommits the first
transaction.
Although you explicitly create two Transaction objects, only one is used. Of course, this creates a
problem. Let's assume you have a Session object being used by two application threads. The first
application thread begins the JTA transaction and starts adding objects. Meanwhile, the second
thread, using the same transaction, deletes an object and commits the transaction. Where does this
leave the first thread?
The first thread won't be committed, which is what you'd expect. The problem is that this issue can
be hard to debug, bringing up an important point: Sessions should be used by only one application
thread at a time. This is a common concern in web applications, which are multithreaded by their
very nature.
Cache providers
As we mentioned earlier, caching is a common method used to improve application performance.
Caching can be as simple as having a class store frequently used data, or a cache can be
distributed among multiple computers. The logic used by caches can also vary widely, but most use
a simple least recently used (LRU) algorithm to determine which objects should be removed from
the cache after a configurable amount of time.
Before you get confused, let's clarify the difference between the Sessionlevel cache, also called
the firstlevel cache, and what this section covers. The Sessionlevel cache stores object instances
for the lifetime of a given Session instance. The caching services described in this section cache
data outside of the lifetime of a given Session. Another way to think about the difference is that the
Session cache is like a transactional cache that only caches the data needed for a given operation
or set of operations, whereas a secondlevel cache is an application-wide cache.
By default, Hibernate supports four different caching services. EHCache (Easy Hibernate Cache) is
the default service. If you prefer to use an alternative cache, you need to set the
cache.provider_class property in the hibernate.cfg.xml file:
<property name="cache.provider_class">
org.hibernate.cache.OSCacheProvider
</property>
This snippet sets the cache provider to the OSCache caching service.
Caching Services Supported by Hibernate
Caching
Service
Provider Class
Type
EHCache
org.hibernate.cache.EhCacheProvider
Memory,disk
OSCache
org.hibernate.cache.OSCacheProvider
Memory,disk
SwarmCache
org.hibernate.cache.SwarmCacheProvider Clustered
TreeCache
org.hibernate.cache.TreeCacheProvider
Clustered
The caching services support the caching of classes as well as collections belonging to persistent
classes. For instance, suppose you have a large number of Attendee instances associated with a
particular Event instance. Instead of repeatedly fetching the collection of Attendee s, you can cache
it. Caching for classes and collections is configured in the mapping files, with the cache element:
<class name="Event"table="events">
<cache usage="read-write"/>
...
</class>
Collections can also be cached:
<set name="attendees">
<cache usage="read-write"/>
98
...
</set>
Once you've chosen a caching service, what do you, the developer, need to do differently to take
advantage of cached objects? Thankfully, you don't have to do anything. Hibernate works with the
cache behind the scenes, so concerns about retrieving an outdated object from the cache can be
avoided. You only need to select the correct value for the usage attribute.
The usage attribute specifies the caching concurrency strategy used by the underlying caching
service. The previous configuration sets the usage to readwrite , which is desirable if your
application needs to update data. Alternatively, you may use the nonstrictreadwrite strategy if
it's unlikely two separate transaction threads could update the same object. If a persistent object is
never updated, only read from the database, you may specify set usage to read-only.
Some caching services, such as the JBoss TreeCache, use transactions to batch multiple operations
and perform the batch as a single unit of work. If you choose to use a transactional cache, you may
set the usage attribute to transactional to take advantage of this feature. If you happen to be using
a transactional cache, you'll also need to set the transaction.manager_lookup_class mentioned in
the previous section.
Readonly
Readwrite
Nonstrict-readTransactional
write
EHCache
OSCache
SwarmCache
TreeCache
Clearly, the caching service you choose will depend on your application requirements and
environment. Next, let's look at configuring EHCache.
Configuring EHCache
By now you're probably tired of reading about configuring Hibernate, but EHCache is pretty simple.
It's a single XML file, placed in a directory listed in your classpath. You'll probably want to put the
ehcache.xml file in the same directory as the hibernate.cfg.xml file.
ehcache.xml file
<ehcache>
<diskStore path="java.io.tmp"/>
<defaultCache
maxElementsInMemory="10"
eternal="false"
timeToIdleSeconds="120"
timeToLiveSeconds="120"
overflowToDisk="true"/>
<cache name="com.manning.hq.ch03.Event"
maxElementsInMemory="20"
eternal="false"
timeToIdleSeconds="120"
timeToLiveSeconds="180"
overflowToDisk="true"/>
</ehcache>
In this example, the diskStore property sets the location of the disk cache store. Then, the listing
declares two caches. The defaultCache element contains the settings for all cached objects that
don't have a specific cache element: the number of cached objects held in memory, whether
objects in the cache expire (if eternal is true , then objects don't expire), the number of seconds an
object should remain the cache after it was last accessed, the number of seconds an object should
remain in the cache after it was created, and whether objects exceeding maxElementsInMemory
should be spooled to the diskStore. Next, for custom settings based on the class, the code defines a
cache element with the fully qualified class name listed in the name attribute. (This listing only
99
demonstrates a subset of the available configuration for EHCache. Please refer to the
documentation found at http:// ehcache.sf.net for more information.)
Inheritance
Inheritance is a fundamental concept of object-oriented languages. Through inheritance, objects
can inherit the state and behavior of their ancestor, or superclass. The most common use of object
inheritance in applications is to create a generic base type with one or more specialized subclasses.
Persisting a class hierarchy can be difficult, since each hierarchy can have its own unique
requirements.
To address the problems found in hierarchy persistence, Hibernate supports three different
inheritance persistence strategies:
Table per class hierarchy
Table per subclass
Table per concrete class
Each mapping strategy is incrementally more complicated. In the following sections, well discuss
the first two inheritance strategies. We've never needed to use the third, and most complicated,
strategy.
Table per class hierarchy
This strategy is the most basic and easiest to use. All the classes in the hierarchy are stored in a
single table. Suppose you have the base Event class, with ConferenceEvent and NetworkingEvent
as subclasses. The mapping definition for this hierarchy is shown in listing 6.
Listing 6. Table per class hierarchy mapping
<class name="Event"table="events"discriminator-value="EVENT">
<id name="id"type="long">
<generator class="native"/>
</id>
<discriminator column="event_type"type="string"length="15"/>
...
<subclass name="ConferenceEvent"discriminatorvalue="CONF_EVENT">
<property name="numberOfSeats"column="num_seats"/>
...
</subclass>
<subclass name="NetworkingEvent"discriminatorvalue="NET_EVENT">
<property name="foodProvided"column="food_provided"/>
...
</subclass>
</class>
We've introduced a few new features in the mapping definition. The most important is the inclusion
of the discriminator element. The discriminator column is what Hibernate uses to tell the different
sub-classes apart when retrieving classes from the database. If you don't specify a discriminator
value, Hibernate uses the object's class name. The discriminator element in the example mapping
tells Hibernate to look in the event_type column for a string describing the class type.
The discriminator is only a column in the relational table-you don't need to define it as a property in
your Java object.
The subclass element contains the properties and associations belonging to the subclass. Any
association element is allowed between sub- class tags. You can't have an id element or a nested
subclass element.
The table per class hierarchy strategy requires a single table, events, to store the three types of
Event instances.
As you can see, one table contains the fields for all the objects in the hierarchy. The only obvious
limitation is that your subclasses cant have columns declared as NOT NULL. Subclasses can't have
non-null attributes because inserting the superclass, which doesnt even have the non-null
attribute, will cause a null column violation when its inserted into the database. The next
inheritance strategy, table per sub-class, doesn't have this limitation.
Table per subclass
Instead of putting all the classes into a single table, you can choose to put each subclass into its
own table. This approach eliminates the discriminator column and introduces a one-to-one mapping
from the sub-class tables to the superclass table. The mapping definition for this strategy is shown
in listing 7.
Table-per-subclass mapping
100
<class name="Event"table="events">
<id name="event_id"type="long">
<generator class="native"/>
</id>
<joined-subclass name="ConferenceEvent"table="conf_events">
<key column="event_id"/>
...
</joined-subclass>
<joined-subclass name="NetworkingEvent"table="net_events">
<key column="event_id"/>
...
</joined-subclass>
</class>
The joined-subclass element can contain the same elements as the subclass element. The key
element contains the primary key associa-tion to the superclass, Event.
<many-to-one class="Event"column="event"/>
Table per concrete class
Since this association can refer to any class in the Event hierarchy, the association is referred to as
a polymorphic association. You can also create a concrete association by giving the name of the
specific subclass:
<many-to-one class="NetworkingEvent"column="event"/>
How To Enable Second Level Caching In Hibernate
First level cache will be enabled by default, but for enable second level cache we need to follow
somesettings, let us see few points regarding this..
When ever we are loading any object from the database, then hibernate verify whether that
object is available in the local cache memory of that particular session [ means first level
cache ], if not available then hibernate verify whether the object is available in global cache or
factory cache [second level cache ], if not available then hibernate will hit the database and loads
the object from there, and then first stores in the local cache of the session [ first level ] then in the
global cache [ second level cache ]
When another session need to load the same object from the database, then hibernate
copies that object from global cache [ second level cache ] into the local cache of this new session
Second level cache in the hibernate is of from 4 vendors
SwarmCache
101
Lets take an example, we have 2 pojo classes in our application like Student, Employee.
If we load student object from the database, then as its the first time hibernate will hits the
database and fetch this student object data and stores in the session1 cache memory [ First level
cache ], then in the global cache [ second level cache ] provided if we write <cache usage=readonly /> in the student mapping file
I mean hibernate will stores in the local session memory by default, but it only stores in the
global cache [ second level cache ] only if we write <cache usage=read-only /> in the student
mapping file, if not so hibernate wont stores in the global cache
Now take another session like session 2 for example, if session 2 also load the student
object then hibernate will loads from the global cache [ second level cache ] as student object is
available at global [Actually when ever we want to load any object hibernate first will checks at
local, then global then database right hope you remembered this ], now if session 3 modify that
student object then hibernate will thorows an error because we have written <cache usage=readonly /> in student mapping file
HQL is to perform both select and non-select operations on the data, but Criteria is only for
selecting the data, we cannot perform non-select operations using criteria
HQL is suitable for executing Static Queries, where as Criteria is suitable for
executing Dynamic Queries
HQL doesnt support pagination concept, but we can achieve pagination with Criteria
With Criteria we are safe with SQL Injection because of its dynamic query generation but in
HQL as your queries are either fixed or parametrized, there is no safe from SQL Injection.
-------------------------Hibernate---------------------------
102
2.What is Hibernate?
Hibernate is an open source, light weight Object Relational Mapping tool to develop the database
independent persistence login in java and j2ee based applications.
Hibernate is a pure Java object-relational mapping (ORM) and persistence framework that allows
you to map plain old Java objects to relational database tables using (XML) configuration and
mapping files. Its purpose is to relieve the developer from a significant amount of relational data
persistence-related programming tasks
3.What is ORM ?
ORM stands for object/relational mapping, means providing the mapping between class with table
and member variables with columns is called ORM. ORM is the automated persistence of objects in
a Java application to the tables in a relational database.
4.hat does ORM consists of ?
An ORM solution consists of the following four pieces:
.
6.Why do you need ORM tools like hibernate?
The main advantage of ORM like hibernate is that it can develop the database independent
persistence logic. Apart from this, ORM provides following benefits:
Improved productivity
o High-level object-oriented API
o Less Java code to write
o No SQL to write
Improved performance
o Sophisticated caching
o Lazy loading
o Eager loading
Improved maintainability
o A lot less code to write
Improved portability
ORM framework generates database-specific SQL for you
103
Load the Hibernate configuration file and create configuration object. It will automatically
load all hbm mapping files because mapping file can be configured in configuration file.
Create session factory from configuration object
Get one session from this session factory
Create HQL Query
Execute query to get list containing Java objects.
104
Programmatic configuration
By using setProperty(-) method of org.hibernate.cfg.Configuration.
First we need to write Java domain objects (beans with setter and getter).
Write hbm.xml, where we map java class to table and database columns to Java class
variables.
Example :
<hibernate-mapping>
<class name="com.durgasoft.EmployeeBean" table="EMPLOYEE">
<id name=eid colume=id/>
<property name="ename" column="NAME" length="255"
not-null="true" type="java.lang.String"/>
<property name="address" column="ADDR" length="255"
not-null="true" type="java.lang.String"/>
</class>
</hibernate-mapping>
17.How do you define sequence generated primary key algorithm in hibernate?
By using <id>, <generator> tags we can configure the primary key and primary key generation
algorithm.
Example:<id name="userid" column="USER_ID" type="java.lang.Long">
<generator class="sequence">
<param name="table">SEQ_NAME</param>
<generator>
</id>
18.What is component mapping in Hibernate?
105
transaction ends. It is also flushed automatically before the transaction commits. You can call
getCurrentSession() as often and anywhere you want as long as the transaction runs. Only the
Session that you obtained with sf.getCurrentSession() is flushed and closed automatically.
openSession() :
If you decide to use manage the Session yourself the go for sf.openSession() , you have to flush()
and close() it.
It does not flush and close() automatically.
Example :
Transaction tx =session.berginTransaction();
Session session = factory.openSession();
try {
tx.begin();
// Do some work
session.createQuery(...);
session.persist(...);
session.flush(); // Extra work you need to do
tx.commit();
}
catch (RuntimeException e) {
tx.rollback();
throw e; // or display error message
}
finally {
session.close(); // Extra work you need to do
}
20.What are the types of Hibernate instance states ?
Three types of instance states:
106
107
Set
List
Array
Map
Bag
sorted collection
order collection
108
</return>
</sql-query>
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 :
109
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>
110
111
112