SlideShare a Scribd company logo
Java/J2EE Programming Training
Hibernate
Page 2Classification: Restricted
Agenda
• Introduction
• Architecture
• The Persistence Lifecycle
• Getting Started
• Relationships and Associations
• Advanced Mapping Concepts
• Hibernate Queries
• Hibernate Transactions
• Hibernate Extensions
Page 3Classification: Restricted
Hibernate Introduction
Page 4Classification: Restricted
Preface
• Most of the modern languages have embraced Object Oriented
Programming (OOP) approach.
• OOP based software architecture promotes separation of concerns
such that each component does only what it is supposed to do.
• Application development should mostly focus on problems in the
application domain, which is the business logic.
• A highly scalable architecture is one with the least amount of direct
dependence between components.
• But most application makes use of relational database to persist
data.
• Somewhere in the guts of the application a database is being
queried and a response is offered.
• While the demand for such applications has grown, their creation
has not become noticeably simpler.
Page 5Classification: Restricted
Persistence
• Persistence of information is one of the most basic requirements in
a software application
• Almost all languages provide ways and methods to persist data.
• J2EE has supported JDBC for persistence since its beginning.
• JDBC has been useful but tends to not allow isolation of business
logic and persistence concerns.
• Some standardization has occurred - the most successful being the
Enterprise JavaBeans (EJB) standard of Java 2 Enterprise Edition
(J2EE), which provides for container- and bean-managed
persistence of entity bean classes.
• Unfortunately, this and other persistence models all suffer to one
degree or another from the mismatch between the relational model
and the object-oriented model.
• In short, database persistence is difficult.
Page 6Classification: Restricted
Plain Old Java Objects (POJOs)
• In our ideal world, it would be trivial to take any Java object and persist it to
the database.
• Object pojoId = value;
• MagicPersistenceSolution magic =
MagicPersistenceSolution.getInstance();
• pojo = magic.get(pojoId);
• POJO pojo = new POJO();
• MagicPersistenceSolution magic =
MagicPersistenceSolution.getInstance();
• magic.save(pojo);
Page 7Classification: Restricted
JDBC Code to Access Relational Data
Impact on an Audience
What you say How you SayWhat is seen
public static String getMessage (int messageId) throws MessageException {
Connection c = null; PreparedStatement p = null; String text = null;
try {
Class.forName(“com.mysql..jdbc.driver");
c = DriverManager.getConnection( "jdbc:mysql://localhost:3306/sample", “root", “admin");
p = c.prepareStatement( "select * from message");
ResultSet rs = p.executeQuery();
while(rs.next()) {
text = rs.getString(1); }
return text;
} catch (Exception e) {
log.log(Level.SEVERE, "Could not acquire message", e);
throw new RunTimeException( "Failed to retrieve message from the database.", e);
} finally {
if (p != null) {
try {
p.close();
} catch (SQLException e) {
log.log(Level.WARNING, "Could not close ostensibly open statement.", e);
}
} if (c != null) {
try {
c.close();
} catch (SQLException e) {
log.log(Level.WARNING, "Could not close ostensibly open connection.", e);
}
}
}
}
Page 8Classification: Restricted
JDBC as a Persistence Solution
• Programming with JDBC requires usage of semantics of the database world.
• JDBC code has its own rules and concerns, which are not aligned with the
business domain.
• Application development should mostly focus on problems in the application
domain, which is the business logic.
• Writing simple JDBC code may be relatively easy, but for complex issues like
caching and clustering, JDBC does not offer anything.
• JDBC code makes business logic developer worry about persistence issues.
Impact on an Audience
What you say How you SayWhat is seen
Page 9Classification: Restricted
EJB Entity Beans as a Persistence Solution
• CMP entity beans require a one-to-one mapping to database tables.
• They do not directly support inheritance relationships.
• They are (by reputation, at least) slow.
• Someone has to determine which bean field maps to which table column.
• They require special method names. If these are not followed correctly, they
will fail silently.
• Entity beans have to reside within a J2EE application server environment—
they are a heavyweight solution.
• They cannot readily be extracted as "general purpose" components for other
applications.
• They are not serializable.
• They rarely exist as portable components to be dropped into a foreign
application—you generally have to roll your own EJB solution.
Impact on an Audience
What you say How you SayWhat is seen
Page 11Classification: Restricted
Hibernate
• Hibernate is an open source ORM framework that is a pioneer and market
leader.
• Hibernate provides ORM solution which is compatible with the latest Java
Persistence API (JPA) specifications.
• Provides transparent persistence, allowing the application to switch between
database vendors or even persistence mechanism.
• Provides complete separation of concerns between domain business logic
and persistence.
• No need to implement any hibernate specific interfaces, APIs or extend
classes from within the domain objects.
Page 12Classification: Restricted
Hibernate Architecture
Page 13Classification: Restricted
Hibernate Architecture
• Applications make use of Hibernate through the interfaces which it provides.
• Hibernate makes itself accessible to the application at the following levels.
• Configuration: Allowing application to configure hibernate.
• Persistence: Allowing application to persist its domain object
over a session in a transaction. Or to retrieve using queries.
• Callback: Allowing application to keep track of hibernate
events.
• Extension: Allowing application to add UserTypes,
IdentifierGenerator.
Page 14Classification: Restricted
Hibernate Architecture
ApplicationLayer
Application Domain Objects (POJO)
Configuration Layer
Persistence Layer
(Session, Transaction, Query,
SessionFactory)
Hibernate
Extensions
Application
Database
Callback Layer
(Interceptor, Validatable, Lifecycle)
Dialect JDBC
Page 15Classification: Restricted
Hibernate Interfaces
• Major interfaces of concern in Hibernate are:
• Session
• SessionFactory
• Configuration
• Transaction
• Query
• Callback
• Types
• Extension
Page 16Classification: Restricted
Session Interface
• Primary interface used by application when interacting with hibernate.
• Found in the package org.hibernate.
• Light weight interface that acts as a persistence manager.
• It is not thread safe and so should be used one per thread.
• Represents one unit of work. In web invocation terms, can be mapped to
one client request.
• The basic level of object cache in Hibernate.
Page 17Classification: Restricted
SessionFactory
• Acts as Factory to the Session objects.
• SessionFactory used across the application.
• One SessionFactory per database.
• Can provide second level of cache for objects across sessions.
Page 18Classification: Restricted
Configuration
• Used for configuring the Hibernate.
• Provides access to the configured SessionFactory.
Page 19Classification: Restricted
Transaction
• An optional API, applications can use its own transaction infrastructure if
desired.
• Provides abstraction over lower level transaction implementation either via
JDBC or JTA.
Page 20Classification: Restricted
Query
• Used for querying database to retrieve objects.
• Provides way to set query parameters and limit result size.
• Comes with a Criteria interface to filter search.
Page 21Classification: Restricted
Callback
• Allows applications to keep track of the events happening in Hibernate.
• Interceptor can be used to react to lifecycle events.
Page 22Classification: Restricted
Callback
• Allows applications to keep track of the events happening in Hibernate.
• Interceptor can be used to react to lifecycle events.
Page 23Classification: Restricted
Types
• Hibernate Types map to the java types of the data stored in the database.
• UserType and CompositeUserType can be used to add domain specific types
to hibernate.
Page 24Classification: Restricted
Extension
• Allows extending hibernate functionalities.
• Commonly used extension interfaces are IdentifierGenerator and Dialect.
Page 25Classification: Restricted
The Persistence Lifecycle
Page 26Classification: Restricted
Lifecycle of Persistence Objects
• The application domain objects (POJO) are the persistent objects.
• The persistence object can be in one of the three states:
• Transient
• Persistent
• Detached
Page 27Classification: Restricted
Lifecycle of Persistent Object
Garbage
collected
Transient
Persistent
Detached
new
get()
load()
find()
iterate()
evict()
close()
clear()
update()
saveOrUpdat
e()
lock()
save()
saveOrU
pdate()
delete()
Page 28Classification: Restricted
Transient Objects
• Any application domain object created using a new() operator is a transient
object and as such a plain java object.
• Any state in such an object is not associated with any database table row.
• If such an object is destroyed without becoming persistent, then no data held
by the object is stored in the database.
• For an object to move from transient state to persistent state requires a call to
save() method of the Persistence Manager.
Page 29Classification: Restricted
Persistent Objects
• An object with its database identifier set is a persistent object.
• Persistent object is always part of a session and is transactional.
• A persistent object can be created by calling save() on the Persistence
Manager.
• Persistent object might be an instance retrieved from the database using
a query.
• Persistent objects participate in transactions and its state is synchronized
with the database at the end of transaction.
Page 30Classification: Restricted
Persistent Objects (contd.)
• When transaction is committed, Persistent object is synchronized with the
database using INSERT, UPDATE or DELETE.
• Persistent object may also be synchronized with database before
execution of a query to get latest data from the database into memory.
Page 31Classification: Restricted
Detached Objects
• A domain object is persistent only in the scope of the session in which it
was created.
• If the session is closed using Session.close() then all persistent objects
that are still referenced after close() are in detached state.
• They are no longer associated with any transaction and will not be
synchronized with the database.
• The data contained in such objects may not be the latest.
Page 32Classification: Restricted
Lifecycle of Persistent Object
Garbage
collected
Transient
Persistent
Detached
new
get()
load()
find()
iterate()
evict()
close()
clear()
update()
saveOrUpdat
e()
lock()
save()
saveOrU
pdate()
delete()
Page 33Classification: Restricted
Object Identity
• In Java, objects are often compared for equality using object identity
(a==b)
• A persistent object may also require comparison of its database identifier,
to establish identity.
• Concept of transient, persistent and detached objects provides different
scopes for objects within which their identities may differ.
Page 34Classification: Restricted
Object Identity (contd.)
• Hibernate supports Transaction-Identity scope.
• If a persistent object is accessed multiple times within a same
transaction, then hibernate ensures that the same instance is always
returned.
• This ensures that within a transaction, application works on the same
data.
• Once a transaction is committed and a session is closed, the resulting
detached object is no longer in the transactional scope.
Page 35Classification: Restricted
Object Identity (contd.)
• Equality between to persistent objects can be best established by proper
implementation of equals() method in the domain class.
• Typical implementation of equals() method will be as follows:-
public class Person {
public boolean equals(Object other) {
if(this == other){
return true;
}
if(id == null){
return false;
}
if(!(other instanceof Person)){
return false;
}
Person person = (Person) other;
return this.id.equals(person.getId());
}
}
Page 36Classification: Restricted
Getting Started with Hibernate
Page 37Classification: Restricted
Hello World
• Create a table called ‘message’:
CREATE TABLE message (
message_id INTEGER UNSIGNED NOT NULL AUTO_INCREMENT,
text VARCHAR(50) NULL,
PRIMARY KEY(message_id)
);
Page 38Classification: Restricted
Hello World
• Create a domain class called ‘Message’:
package com.csc.training.sample.model;
public class Message {
private Long id;
private String message;
public Message(){}
public Message(String message){
this.message = message;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getMessage() {
return message;
}
public String setMessage(String message) {
return this.message = message;
}
}
Page 39Classification: Restricted
Hello World
• Create a class and property mapping file called ‘Message.hbm.xml’ and
place it in the classpath:
<?xml version="1.0" encoding="UTF-8"?>
<!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.csc.training.sample.model.Message" table="message">
<id name="id" column="message_id">
<generator class="increment"/>
</id>
<property name="message" column="text"/>
</class>
</hibernate-mapping>
Page 40Classification: Restricted
Hello World
• Create a Data Access Object (DAO) class called ‘MessageDAO’:
package com.csc.training.sample.dao;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import com.csc.training.sample.model.Message;
public class MessageDAO {
public void createMessage(String msg){
Session session = getSessionFactory().openSession();
Transaction tx = session.beginTransaction();
Message message = new Message(msg);
session.save(message);
tx.commit();
session.close();
}
private SessionFactory getSessionFactory() {
Configuration configuration = new Configuration();
configuration.addResource("com/csc/training/sample/model/Message.hbm.xml");
return configuration.buildSessionFactory();
}
}
Page 41Classification: Restricted
Hello World
• Create a Test class of the DAO called ‘MessageDAOTest’:
package com.csc.training.sample.dao;
public class MessageDAOTest {
public static void main(String[] args){
MessageDAO dao = new MessageDAO();
dao.createMessage("Hello World");
}
}
Page 42Classification: Restricted
Hello World
• Create the configuration file called ‘hibernate.properties’:
hibernate.connection.driver_class=com.mysql.jdbc.Driver
hibernate.connection.url=jdbc:mysql://localhost:3306/sample
hibernate.connection.username=root
hibernate.connection.password=admin
hibernate.dialect=org.hibernate.dialect.MySQLInnoDBDialect
Page 43Classification: Restricted
Hello World
• Add following jars to classpath:
• antlr-2.7.6.jar
• asm.jar
• cglib-2.1.3.jar
• commons-collections.jar
• commons-logging-1.1.jar
• dom4j-1.6.1.jar
• hibernate3.jar
• jta.jar
• mysql-connector-java-3.0.9-stable-bin.jar
• oscache-2.3.2.jar
Page 44Classification: Restricted
Hello World
• Run the app with main method in the MessageDAOTest class.
• The data should be inserted in the database.
Page 45Classification: Restricted
Hibernate Relationships and
Associations
Page 46Classification: Restricted
Data relationships
• Most of the data found in application domain are related to each other.
• Relational databases are efficient in mapping these relations using foreign
keys.
• Using Hibernate to map to such data from the object model requires special
consideration.
• The types of relations typically observed in the relational database world
are:
• One-to-One relationship
• One-to-Many relationship
• Many-to-One relationship
• Many-to-Many relationship
Page 47Classification: Restricted
Object associations
• In the world of OOP the relations between entities are more commonly
implemented using associations that can be:
• Composition
• Inheritance
Page 48Classification: Restricted
One-to-One relations using foreign key
• The relational data can have a one-to-one relationship as can be seen
between a person and her address.
Page 49Classification: Restricted
One-to-One relations using foreign key
• In this case the domain object model will have a corresponding Person class
referencing an Address object as a property.
• When a Persistent instance of Person class is loaded, the persistent instance
of its referenced Address instance should also be loaded appropriately.
• To enable this, the two classes should be mapped appropriately.
Page 50Classification: Restricted
One-to-One relations using foreign key
package com.sample.hibernate.model;
public class Person {
private int id;
private Address billingAddress;
private String name;
public boolean equals(Object
other){
if(this==other)return true;
if(id==null) return false;
if(!(other instanceof Person))
return false;
Person person = (Person)
other;
return
this.id.equals(person.getId());
}
}
package com.sample.hibernate.model;
public class Address {
private String lane;
private String city;
private String state;
}
Page 51Classification: Restricted
One-to-One relations using foreign key
• For foreign key association, Hibernate does not distinguish between One-
to-One and One-to-many relations and in this case we use the <many-
to-one> tag for mapping the one-to-one relation.
• In this example, the mapping file for Person class will have the following
entry:
<many-to-one name="billingAddress"
class="com.sample.hibernate.mode.Address"
column="Address_id"
cascade="save-update"/>
Person.hbm.xml
Page 52Classification: Restricted
One-to-One relations using foreign key (Bi-
directional)
• In the previous example, there was only one way navigation from Person
to Address.
• If we would like to go back to Person instance from Address, then there
should be a reference to Person in Address class, which will be mapped
as follows.
<one-to-one name=“person"
class="com.sample.hibernate.mode.Person"
property-ref=“billingAddress"/>
Address.hbm.xml
• This will ensure that the Address instance will hold reference to its
appropriate Person instance so that bi-directional navigation can be
achieved.
Page 53Classification: Restricted
One-to-One relations using primary key
• The one-to-one relation can also be established through primary key
association.
• The primary key will also act as a foreign key in this case
Page 54Classification: Restricted
One-to-One relations using primary key
• In this case it must be ensured that the newly created Address objects
have the same key as the Person for which it is created.
• The mappings in this case will be:
Person.hbm.xml
<one-to-one name="billingAddress"
class="com.sample.hibernate.mode.Address"
cascade="save-update"/>
Address.hbm.xml
<one-to-one name=“person"
class="com.sample.hibernate.mode.Person"
constrained=“true"/>
• Constrained attribute tells Hibernate that the Address has a foreign key
constraint on its primary key and it refers to the Person primary key.
Page 55Classification: Restricted
One-to-One relations using primary key
• To ensure that newly saved Address instances are assigned the same
primary key as that of the person, a special identifier-generator needs to
be used.
Address.hbm.xml
<class name="com.sample.hibernate.mode.Address"
table="Address">
<id name="id" column="Person_id" >
<generator class="foreign">
<param name="property">
person
</param>
</generator>
</id>
• The property “person” of the new Address object is used to get the
identifier which is assigned to the Address identifier.
Page 56Classification: Restricted
One-to-Many relations - Unidirectional
• For unidirectional navigation, the item class will hold a collection of bids.
• The relationship will be mapped using the <set> element.
Item.hbm.xml
<set name="bids“ table=“Bid”>
<key column="Item_ID"/>
<one-to-many class="Bid"/>
</set>
Page 57Classification: Restricted
One-to-Many relations – Bidirectional
• For bidirectional navigation, the Bid class will hold the item for which the
bid is created.
• The item property can be mapped as follows.
Bid.hbm.xml
<many-to-one name=“item"
column="Item_ID“
class=“Item”
not-null=“true"/>
Page 58Classification: Restricted
Many-to-Many relations - Unidirectional
• A many to many relation should ideally make use of a link table.
• The link table will have foreign keys to the primary keys of the original
table.
Page 59Classification: Restricted
Many-to-Many relations - Unidirectional
• The category class in this case will hold reference to the Item in
the form of collection of value types.
• The link table will have foreign keys to the primary keys of the
original table.
Category.hbm.xml
<set name="items"
table="CATEGORY_ITEM"
lazy="true"
cascade="save-update“>
<key column="category_id"/>
<many-to-many class="Item" column="Item_ID"/>
</set>
Page 60Classification: Restricted
Many-to-Many relations - Bidirectional
• Item class holds reference to categories as well.
Item.hbm.xml
<set name=“categories"
table="CATEGORY_ITEM"
lazy="true“
inverse=“true”
cascade="save-update"
<key column=“Item_ID"/>
<many-to-many class=“Category“
column=“Category_ID"/>
</set>
Page 61Classification: Restricted
Advanced Mapping Concepts
Page 62Classification: Restricted
Hibernate type system
• When working with hibernate, we have to deal with two data
types:
• The data type of the underlying database
• The Java data types
• The Java types need to be mapped to the data types in the
database
• In the mapping files, the types are mapped as follows
• <property name=“email” column=“EMAIL” type=“string”/>
Page 63Classification: Restricted
Built-in mapping types
 Hibernate comes with in built-in mapping types for various Java and SQL
types
CHAR(1) (‘T’ or ‘F’)Boolean or java.lang.BooleanTrue_false
CHAR(1) (‘Y’ or ‘N’)Boolean or java.lang.BooleanYes_no
BITBoolean or java.lang.BooleanBoolean
TINYINTByte or java.lang.ByteByte
VARCHARJava.lang.StringString
CHAR(1)Java.lang.StringCharacter
NUMERICJava.math.BigDecimalBig_decimal
DOUBLEDouble or java.lang.DoubleDouble
SMALLINTShort or java.lang.ShortShort
BIGINTLong or java.lang.LongLong
INTEGERInt or java.lang.Integerinteger
SQL typeJava typeMapping type
Page 64Classification: Restricted
Built-in mapping types
 The built in data type for dates and times are
DATEJava.util.CalendarCalendar_date
TIMESTAMPJava.util.CalendarCalendar
TIMESTAMPJava.util.Date or
java.sql.Timestamp
Timestamp
TIMEJava.util.Date or java.sql.TimeTime
DATEJava.util.Date or java.sql.DateDate
SQL typeJava typeMapping type
Page 65Classification: Restricted
Built-in mapping types
 The built in data type for large object mappings are
BLOBJava.sql.BlobBlob
CLOBJava.sql.ClobClob
VARBINARY (or BLOB)Any java class that implements
Serializable
Serializable
CLOBJava.lang.StringText
VARBINARY (or BLOB)Byte[]Binary
SQL typeJava typeMapping type
 The java.sql.Blob or java.sql.Clob may be the most efficient way of
handling large objects
 But these may not be supported by drivers for all databases
 If a Blob or Clob is referenced in a persistent class, then they will
only be available in a transaction and not when it is in detached
state
Page 66Classification: Restricted
Mapping Inheritance
 Inheritance is a very powerful OOP concept and is used quite often in
applications
 Relational database does not support inheritance. It only establishes
relations using foreign keys
 For scenarios where the application domain object has an inheritance type
of relationship, there are a few things to be considered while creating the
mapping.
Page 67Classification: Restricted
 Consider a case where an application has multiple billing options
 Credit card
 Bank account
 In this case, the user name and details are same, only the type specific
details differ
CreditCard
Type:int
expMonth:String
expYr:String
BankAccount
Name:String
Swift:string
BillingDetails
Owner:String
number:String
Created:Date
Mapping Inheritance
Page 68Classification: Restricted
 One of the strategies that can be applied is Table per concrete class
 In this case, the user name and details are same, only the type specific
details differ
 This is a little inefficient as two queries are needed to fetch the details
Table per Concrete Class
Page 69Classification: Restricted
 Another strategy that can be applied is table per hierarchy
 A single table representing all the details
 Although there is a single table the classes will still be separate
Table per Hierarchy
Page 70Classification: Restricted
 The mappings for the table per hierarchy will make use of the <subclass>
element
 This approach requires all properties of credit card and bank details to be
nullable.
<hibernate-mapping>
<class name="BillingDetails“ table="BillingDetails">
<id name="id" column="BillingDetailsId">
<generator class="increment"></generator>
</id>
<discriminator column=“BILLINGTYPE” />
<subclass name="CreditCard" discriminator-value="CC">
<property name=“ccnumber" column=“number"/>
</subclass>
<subclass name="BankAc" discriminator-value="Bank">
<property name=“acnumber” column=“number”/>
</subclass>
</class>
</hibernate-mapping>
Table per Hierarchy
Page 71Classification: Restricted
 Another strategy that can be applied is table per subclass
 The tables contain only the required columns and a foreign key to
the BillingDetails
 The foreign key also acts as the primary key of the table
Table per Subclass
Page 72Classification: Restricted
 A <joined-subclass> element is used to indicate table-per subclass mapping
<class name="BillingDetails“ table="Billing_Details">
<id name="id" column="id">
<generator class="increment“/>
</id>
<joined-subclass name="CreditCard" table="CreditCardDetails">
<key column="Billing_Details_Id"/>
<property name="cctype" column="cctype"/>
</joined-subclass>
<joined-subclass name=“BankAc" table=“BankAcDetails">
<key column="Billing_Details_Id"/>
<property name=“swift" column=“swift"/>
</joined-subclass>
</class>
Table per Subclass
Page 73Classification: Restricted
Hibernate Queries
Page 74Classification: Restricted
Queries
• Queries are most important for writing good data access code
• Hibernate provides extensive support for querying using its Query
interface
• Hibernate uses powerful language Query Language called HQL
(Hibernate Query Language)
• Queries are in terms of classes and properties and not tables and
columns
• Hibernate also supports execution of native SQL queries
Page 75Classification: Restricted
Queries
• Queries can be created on a session
• Query hqlQuery = session.createQuery(“from Person”);
• Queries support pagination by limiting results
• Query query = session.createQuery(“from User”);
Query.setFirstResult(0);
Query.setMaxResults(10);
Page 76Classification: Restricted
Queries:Example
Query query = session.createQuery("from Employees");
query.setFirstResult(1);
query.setMaxResults(10);
List<Employees> empList = query.list();
for( Employees e:empList)
{
System.out.println( e );
}
Page 77Classification: Restricted
Queries
• Queries use the Criteria interface for filtering
searches based on criteria
• Session.createCriteria(Category.class).add(Expression.like(“
name”, “Laptop%”));
• list() method executes the created query and
returns the results as a list
• List result = session.createQuery(“from User”).list();
Page 78Classification: Restricted
Queries:Example
public static void criteriaTest(Session session) {
session.getTransaction().begin();
Criteria criteria = session.createCriteria(Departments.class);
criteria.add(Restrictions.eq("departmentName",
"Accounting"));
List<Departments> departmentList = criteria.list();
for (Departments d : departmentList) {
System.out.println(d);
}
session.getTransaction().commit();
}
Page 79Classification: Restricted
Named Queries
• Named queries help in avoiding HQL queries to be located within Java
files.
• The queries to be used in an application can be externalized in an XML
mapping file.
• The desired query can be referred to by the name.
• The getNamedQuery() method is used to obtain a Query instance for a
named query given its name.
• Named queries allow easier optimization of queries.
session.getNamedQuery("findItemsByDescription").
setString("description", description).list();
<query name="findItemsByDescription">
<![CDATA[from Item item where item.description like :description]]>
</query>
Page 80Classification: Restricted
Named Queries:Example
public static void findDeptByName(Session session) {
session.getTransaction().begin();
List<Departments> departmentList =
session.getNamedQuery("findDepartmentByName")
.setString("deptName", "Accounting").list();
Departments d = departmentList.get(0);
System.out.println(d);
session.getTransaction().commit();
}
departments.hbm.xml
<query name="findDepartmentByName">
<![CDATA[from Departments d where d.departmentName = :deptName]]>
</query>
Page 81Classification: Restricted
The Query API
 The Query interface of hibernate is used for retrieving the data from
database
 Criteria interface is for specifying query criteria
 Query hquery = session.createQuery()
 Criteria crit = session.createCriteria()
Page 82Classification: Restricted
Binding Parameters
 For passing parameters to a query, the following approaches can be used
 Named Parameter
 Positional Parameter
 Named Parameter
 Allows you to specify the name of the expected parameter
 String query = “from Item where description like :searchString”
 In this case “searchString” is the named parameter
 Query qu = session.createQuery(query).
setString(“searchString”, searchString);
Page 83Classification: Restricted
Binding Parameters:Example
public static void bindingParameter(Session session) {
String sql = "from Employees where employeeId = :empID";
session.getTransaction().begin();
Query query = session.createQuery(sql);
query.setInteger("empID", 100);
Employees e = (Employees) query.uniqueResult();
System.out.println(e);
session.getTransaction().commit();
ses
Page 84Classification: Restricted
 Positional Parameter
 Allows you to specify the parameter position using “?” like prepared
statements
 String query = “from Item item where item.description like ? and
item.date > ?”
 Query qu = session.createQuery(query).setString(0,
searchString).setDate(1,minDate);
Binding Parameters
 As seen in the above examples, the setString() and setDate() methods were
used, Hibernate also allows setting of various other types as well as entity:
Session.createQuery(“from item where item.seller = :seller”).
setEntity(“seller”, seller);
Page 85Classification: Restricted
public static void bindingParameter1(Session session) {
String sql = "from Employees where departments = :dept";
session.getTransaction().begin();
Query query = session.createQuery(sql);
short s =50;
query.setEntity("dept",session.get(Departments.class, s ) );
List<Employees> empList = query.list();
for(Employees e:empList)
{ System.out.println(e );
// System.out.println(e.getDepartments()); }
session.getTransaction().commit();
session.close();
}
Binding Parameters:Example
Page 86Classification: Restricted
Ordering query results
 For ordering the results obtained from queries, Hibernate provides order
by clause
 “from User u order by u.username”
 “from User u order by u.username desc”
 The Criteria API also provides ordering
 Session.createCriteria(User.class).
addOrder(Order.asc(“lastname”));
Page 87Classification: Restricted
Association
 The hibernate query language supports performing queries on associations
 Join can be used to combine data in two (or more) relations
 HQL provides four ways of expressing joins
 An ordinary join in the from clause
 A fetch join in the from clause
 An implicit association join
 A theta-style join in the where clause
Page 88Classification: Restricted
 A fetch join can be used to specify that an association should be eagerly
fetched
from Item item join fetch item.bids
where item.description like “%computer%”;
Fetch Join
 An alias can be to make query less verbose
from Item item join fetch item.bids bid
where item.description like “%computer%”
and bid.amount > 100;
 We can do the same thing using the Criteria API
session.createCriteria(Item.class).
setFetchMode(“bids”, FetchMode.EAGER).
add(Expression.like(“description”, “computer”,
MatchMode.ANYWHERE).
list();
Page 89Classification: Restricted
Implicit Association
 HQL supports multipart property path expressions for two purposes:
 Querying components
from User u where u.address.city=“city”
Session.createCriteria(User.class).
add(Expression.eq(“address.city”, ”city”);
 Expressing implicit association joins
from Bid bid where bid.item.description like ‘%computer%’;
 Implicit joins are directed towards only on many-to-one or
one-to-one association.
 Its available only on HQL
Page 90Classification: Restricted
Theta Style Join
• Theta style joins are to perform joins between two un-associated
classes:
from User , Category (Cartesian Product)
from User user, Category category where user.username =
category.createdBy;
• This will return an Object[] with 2 elements
• Object[0] -> User
• Object[1] -> Category
Page 91Classification: Restricted
Aggregation
 The hibernate query language supports performing various aggregation of
the results
 The supported aggregation functions are
 avg(...), sum(...), min(...), max(...)
 count(*), count(...), count(distinct ...)
 count(all...)
Select count(*) from Item
Select sum(amount) from Bid
Page 92Classification: Restricted
Grouping
 Any property or alias appearing in an HQL outside the aggregate function
can be used for grouping results
select u.lastname, count(u) from User u group by u.lastname
Here the results will be grouped according the user’s last name.
 Grouping can be restricted using the having clause
select u.lastname, count(u) from User u group by u.lastname having
user.lastname like ‘A%’
Page 93Classification: Restricted
Sub-queries
 In the databases that support sub-selects, Hibernate supports sub-queries
 Sub-queries allow a select query to be embedded in another query
from User u where 10 <
(select count(i) from u.items I where i.successfulBid is not null)
This returns all the users who have bid successfully more than 10 times.
Page 94Classification: Restricted
Native Queries
 Hibernate provides support for making use of native SQL queries instead of
HQL.
 The SQL query results return the entity instance just like hibernate queries.
Page 95Classification: Restricted
Native Queries
 SQL query may return multiple entity instances
 SQL query may return multiple instances of same entity
 Hibernate needs to distinguish between different entities
 Hibernate uses a naming scheme for the result column aliases to correctly
map column values to the properties of particular instances
Page 96Classification: Restricted
Scalar Queries
• SQL queries can be used to return a list of scalars
String sql = “select * from appuser”;
sesssion.createSQLQuery(sql)
.addScalar("username", Hibernate.STRING)
.addScalar("name", Hibernate.STRING)
.list();
• This will return the scalar values as List of Object[]
Page 97Classification: Restricted
Entity Queries
• Hibernate can also allow you to obtain Entity instances using SQL
queries
• The SQL queries will need to be supplied with the Entity that represents
the table
String sql = “select * from address”;
Session.createSQLQuery(sql).addEntity(Address.class);
Page 98Classification: Restricted
Handling Associations
• When an entity has a many-to-one relation with another, then it is
required to return the association or else a column not found error will
be returned.
• A * notation will return the association
String sql = "select * from user";
session.createSQLQuery(sql)
.addEntity(User.class)
.list();
Page 99Classification: Restricted
Returning Non-Managed Entities
• SQL can be used to return non-managed entities
• The entity instances returned may not reflect the latest values over a
session
String sql = "select lane, city from address where city like ?";
session.createSQLQuery(sql)
.setResultTransformer(
Transformers.aliasToBean(Address.class))
.setString(0, cityName)
.list();
Page 100Classification: Restricted
Named SQL Query
• SQL queries can be written externally and accessed in the code
• Named queries allow more flexibility to modify queries
<sql-query name="cityQuery">
<return-scalar column="city" type="string"/>
<return-scalar column="lane" type="string"/>
<![CDATA[
SELECT a.city AS city, a.lane AS lane
FROM Address a
WHERE a.city LIKE :cityName
]]>
</sql-query>
Page 101Classification: Restricted
Stored Procedure
• Hibernate from version 3 introduces support for queries via stored
procedures and functions.
• The stored procedure/ function must return a resultset as the first out-
parameter to be able to work with Hibernate.
CREATE OR REPLACE FUNCTION selectAllEmployments
RETURN SYS_REFCURSOR
AS
st_cursor SYS_REFCURSOR;
BEGIN
OPEN st_cursor FOR
SELECT EMPLOYEE, EMPLOYER, STARTDATE, ENDDATE,
REGIONCODE, EID, VALUE, CURRENCY
FROM EMPLOYMENT;
RETURN st_cursor;
END;
Page 102Classification: Restricted
Stored Procedure
• To use the stored procedure, map it through a named query
<sql-query name="selectAllEmployees_SP" callable="true">
<return alias="emp" class="Employment">
<return-property name="employee" column="EMPLOYEE"/>
<return-property name="employer" column="EMPLOYER"/>
<return-property name="startDate" column="STARTDATE"/>
<return-property name="endDate" column="ENDDATE"/>
<return-property name="regionCode" column="REGIONCODE"/>
<return-property name="id" column="EID"/>
<return-property name="salary">
<return-column name="VALUE"/>
<return-column name="CURRENCY"/>
</return-property>
</return>
{ ? = call selectAllEmployments() }
</sql-query>
Page 103Classification: Restricted
Custom SQL
• Hibernate3 can use custom SQL statements for create, update, and
delete operations
• The class and collection persisters in Hibernate already contain a set of
configuration time generated strings (insertsql, deletesql, updatesql etc)
• The mapping tags <sql-insert>, <sql-delete>, and <sql-update> override
these strings
Page 104Classification: Restricted
Custom SQL
• The custom SQL script can also invoke a stored procedure if any
• <sql-insert callable="true">
{call createUser (?, ?)}
</sql-insert>
• <sql-delete callable="true">
{? = call deleteUser (?)}
</sql-delete>
• The positioning of parameters are important and should be as per what
Hibernate expects
Page 105Classification: Restricted
Hibernate Transactions
Page 106Classification: Restricted
Transaction
• Most enterprise applications working with the database systems need
to make use of transactions for data integrity
• In an application program, the database transactions should be of as
short duration as possible
• Ideally, the transaction should be in affect when the application is
dealing with the database and not when it is interacting with the user
Page 107Classification: Restricted
Transaction
• Java through JDBC and J2EE though JTA have provided powerful support
for transactions.
• Hibernate acts as a client to the JDBC and JTA transactions, allowing the
application to make use of the features while not worrying about the
technical complexities.
Page 108Classification: Restricted
Hibernate Transaction API
• The Transaction interface of hibernate provides methods to define the
transaction boundaries
• The transaction is created on the session
• Transaction tx = session.beginTransaction();
• The commit() method makes performs the database commit
• tx.commit();
• In case of failure, rollback() method should be used to rollback the
changes
• tx.rollback();
Page 109Classification: Restricted
Flushing Hibernate Session
• Changes made to persistent object in a session are stored in memory
• Session implements transaction write behind whereby the changes are
written to database in a transparent manner and to reduce database
access
• Flushing of state occurs in the following cases
• When a transaction is committed
• Before a query is executed
• When application calls session.flush()
Page 110Classification: Restricted
Transaction Isolation Levels
• The transaction isolation levels attempt to segregate concurrent
transactions and their view of the database state
• The isolation levels are implemented by the database vendors, either
using locking or multi-version concurrency control
• Hibernate makes use of the underlying database implementation and
does not on its own add any semantics
Page 111Classification: Restricted
Optimistic locking in application
• Most enterprise applications prefer to use optimistic locking
• Optimistic locking assumes there won’t be any conflicts and data will
not be updated simultaneously
• Optimistic locking can be implemented by using Version number or
TimeStamp
• When using Version, a column should be added to the table and
mapped to a property in the POJO class
<version name=“version” column=“VERSION” />
• Whenever the object is changed, hibernate will automatically update
the version number
Page 112Classification: Restricted
Optimistic locking in application
• When a transaction retrieves an object, its version number is also
fetched
• While the object is in detached state, if the corresponding record is
updated by another transaction, then the version number in the
detached object will be older
• Any update issued for this detached object will result in failure since the
update query will check for the current version in table to be same as
the version number in the detached instance, which will fail with
StaleObjectStateException
Page 113Classification: Restricted
Example
hibernate.transaction.factory_class
net.sf.hibernate.transaction.JDBCTransactionFactory
net.sf.hibernate.transaction.JTATransactionFactory
hibernate.transaction.manager_lookupclass
Vendor specific and you only need to specify the manager lookup class when
you're using a transactional cache.
net.sf.hibernate.transaction.JbossTransactionManagerLookup
net.sf.hibernate.transaction.WeblogicTransactionManagerLookup
Page 114Classification: Restricted
Conversation
To disconnect from the database server, we execute the code:
session.disconnect();
At this point, session object is still valid and will be tracking any changes we
make to the objects previously loaded to the application through the
Session object;
When the application gets control back, it will reconnect to the database
using the code: session.reconnect();
Page 115Classification: Restricted
Hibernate Extensions
Page 116Classification: Restricted
Custom Mapping Types
 Hibernate allows creation of custom value types for the application
domain
 Some of the data in the database may be stored within multiple columns,
but in the object model it may be better to represent it as a class
 Example, for a multi currency payment system, the data may be
stored as
Page 117Classification: Restricted
Custom Mapping Types
 It may be desirable that the amount is always represented in the same
currency, say USD in a separate class like MonetaryAmount even though
the database has no support for it.
public class MonetaryAmount implements Serializable{
private final BigDecimal value;
private final Currency currency;
public MonetaryAmount(final BigDecimal value, final Currency currency) {
this.value = value;
this.currency = currency;
}
public Currency getCurrency() {
return currency;
}
public BigDecimal getValue() {
return value;
}
public boolean equals(Object o){ …… }
public int hashCode() { …… }
public static MonetoryAmount convert(MonetoryAmount sourceAmount, Currency
targetCurrency){…… }
}
Page 118Classification: Restricted
Custom Mapping Type
 To implement a custom user type, the type class needs to
implement the interface org.hibernate.usertype.UserType
public class MonetaryAmountUserType implements UserType {
private static final int[] SQL_TYPES = {Types.NUMERIC};
public int[] sqlTypes() { return SQL_TYPES;}
public Class retunedClass() { return MonetoryAmount.class;}
public boolean equals(Object x, Object y){
if(x == y) return true;
if(x == null || y == null) return false;
return x.equals(y);
}
public Object deepCopy(Object value) { return value;}
public Object isMutable() { return false;}
public Object nullSafeGet(ResultSet resultSet, String[] names, Object owner)
throws HibernateException, SQLException{
if(resultSet.wasNull()) return null;
BigDecimal valueInUSD = resultSet.getBigDecimal(names[0]);
return new MonetoryAmount(valueInUSD, Currency.getInstance(“USD”));
}
Page 119Classification: Restricted
Custom Mapping Types
 To property with the custom type can now be mapped in the class as
below
<property name=“amount” column=“Amount”
type=“com.sample.hibernate.model. MonetaryAmountUserType”/>
public Object nullSafeSet(PreparedStatement statement, Object value,
int index)
throws HibernateException, SQLException{
if(value == null){
statement.setNull(index, Types.NUMERIC);
}else{
MonetoryAmount anyCurrency = (MonetoryAmount) value;
MonetoryAmount amountInUSD = MonetoryAmount.convert(
anyCurrency, Currency.getInstance(“USD”);
statement.setBigDecimal(index, amountInUSD.getValue());
}
}
}
Page 120Classification: Restricted
Hibernate Cache
Hibernate Basics
Page 121Classification: Restricted
Hibernate Cache
 One of the benefits of using Hibernate is its ability to cache the instances
 Caching of data in entity instances can provide great performance benefits
 Hibernate provides configurable caching, where each class can be
separately enabled for caching depending on its usage
 Hibernate provides caching at multiple levels
Page 122Classification: Restricted
Session
First Level Cache
Second Level Cache
Cache
Strategy
Query Cache
Cache Provider
Hibernate Cache Architecture
Page 123Classification: Restricted
 The hibernate cache provides caching at two levels
 The first level cache is the Session Cache which is enabled by default and
can not be disabled
 The second level cached can be chosen between
 Process Cache – shared between many unit of work (transaction)
 Clustered Cache –shared between multiple process on same/multiple
systems.
Hibernate Cache Architecture
Page 124Classification: Restricted
First Level Cache
 All the persistence instances that are in Persistent state stay in the First
Level Cache
 Changes made in a unit of work are cached in the first level cache
 Changes made to object are written to database only on flush()
 You can opt to not keep data in first level cache by using evict() method
 Not useful for application that deal with bulk or large quantity of data. In
such case, we are better off using plain SQL or stored procedures
Page 125Classification: Restricted
Second Level Cache
 The second level cache is at a higher level and allow data to be shared
across the application if opting for Process cache
 The cluster cache is across multiple servers and relies on remote
communication to synchronize the cache
 The second level cache stores data in the form of values
 A Class can be enabled for caching by indicating it in the mapping file
 Disable second level cache by setting
hibernate.cache.use_second_level_cache = false in hibernate.cfg.xml
Page 126Classification: Restricted
Example
To eanable caching include
<property
name="hibernate.cache.provider_class">org.hibernate.cache.EhCacheProvi
der</property>
In hibernate.cfg.xml file.
Create ehcache.xml file
it may be hbm specific or a default one.
Page 127Classification: Restricted
<ehcache>
<diskStore path="java.io.tmpdir"/>
<defaultCache
maxElementsInMemory="1000“
eternal = true/false
timeToIdleSeconds="120"
timeToLiveSeconds="120"
overflowToDisk="true"
/>
<cache name="example.survey.Survey"
maxElementsInMemory="1000“
eternal = true/false
timeToIdleSeconds="3600"
overflowToDisk="false"
/>
</ehcache>
Page 128Classification: Restricted
<class
name="example.survey.Survey“ table="SURVEYS">
<cache usage="read-write"/>
<class>
Read-Only Cache Usage
If your application’s Session object will be loading various classes and the
classes don’t and won’t
change during the execution of the application, you can use the read-only
cache usage.
Else read-write
Page 129Classification: Restricted
Query Cache
To enable query cache use
hibernate.cache.use_query_cache=”true” in hibernate.cfg.xml
Session session = SessionFactory.openSession();
Query query = session.createQuery("from Survey");
query.setCacheable(true);
query.setCacheRegion("surveys");
List users = query.list();
SessionFactory.closeSession();
Page 130Classification: Restricted
Controlling second level cache
You can manage the SessionFactory second-level cache using the following
methods:
public void evict(Class class);
public void evict(Class class, Serializable id);
public void evictCollection(String name);
public void evictCollection(String name, Serializable id);
The primary role of each of these methods is to permanently remove objects
from the cache.
Page 131Classification: Restricted
Controlling session cache
public void evict(Object object);
Clears the object from the cache
public void clear();
Clears entire cache.
boolean contains(Object object);
Returns true/false
Page 132Classification: Restricted
When not to use caching
If your database is being modified by multiple applications, then Hibernate
won’t be able to ensure that the data is valid.
Some data is retrieved and then not reused so that the data expires from the
cache. In this case,there is no point in caching the information and taking
up more memory.
You’re loading very large numbers of objects. If you’re loading and parsing
millions of objects then there may not be enough memory available to
cache them.
Page 133Classification: Restricted
Filters
Dynamic data filtering is related to data security.
<class name="Item" table="ITEM">
...
<filter name="limitItemsByUserRank"
condition=":currentUserRank >=
(select u.RANK from USER u
where u.USER_ID = SELLER_ID)"/>
</class>
Filter filter = session.enableFilter("limitItemsByUserRank");
filter.setParameter("currentUserRank", loggedInUser.getRanking());
Page 134Classification: Restricted
Interceptor
• An interceptor can be used to intercept the existing business functionality
to provide extensible or add-on features
• They provide pluggable architecture and are generally callback methods
that will be called by the framework in response to a particular set of
events/actions if properly registered and configured.
• Example
EmptyInterceptor override
public boolean onSave(Object entity,
Serializable id,
Object[] state,
String[] propertyNames,
Type[] types)
throws CallbackException {
}
Page 135Classification: Restricted
And
public boolean onFlushDirty(Object entity,Serializable id,Object[]
currentState, Object[] previousState, String[] propertyNames,
Type[] types) throws CallbackException {
}
Page 136Classification: Restricted
Projection
The ability to retrieve only properties of an entity or entities, without the
overhead of loading the entity itself into the persistence context. This is
sometimes called a report query; it is more correctly called projection.
Criteria crit = sess.createCriteria(ClassName.class);
ProjectionList proList = Projections.projectionList();
proList.add(Projections.property(“prop1"));
proList.add(Projections.property(“prop2"));
crit.setProjection(proList);
List list = crit.list();
Page 137Classification: Restricted
N+1 selection problem
The following example code tries to find the highest Bids for all Items
List<Item> allItems = session.createQuery("from Item").list(); 1 query n rows
Map<Item, Bid> highestBids = new HashMap<Item, Bid>();
for (Item item : allItems) {
Bid highestBid = null;
for (Bid bid : item.getBids() ) { // Initialize the collection 1 qery
if (highestBid == null)
highestBid = bid;
if (bid.getAmount() > highestBid.getAmount())
highestBid = bid;
}
highestBids.put(item, highestBid);
}
Page 138Classification: Restricted
Solution
A first solution could be a change of your global mapping metadata for the
collection, enabling prefetching in batches:
<set name="bids"
inverse="true"
batch-size="10">
<key column="ITEM_ID"/>
<one-to-many class="Bid"/>
</set>
•2nd
strategy fetch="join“
•fetch="subselect“ one query to find all the items 2nd
to fetch all the bids
Page 139Classification: Restricted
The Cartesian product problem
This Cartesian product problem always appears if you try to fetch several
“parallel” collections
<class name="Item">
...
<set name="bids"inverse="true“ fetch="join">
<key column="ITEM_ID"/>
<one-to-many class="Bid"/>
</set>
<set name="images“ fetch="join">
<key column="ITEM_ID"/>
<composite-element class="Image">...
</set>
</class>
Page 140Classification: Restricted
select item.*, bid.*, image.*
from ITEM item
left outer join BID bid on item.ITEM_ID = bid.ITEM_ID
left outer join ITEM_IMAGE image on item.ITEM_ID = image.ITEM_ID
Page 141Classification: Restricted
Thank You

More Related Content

What's hot

Ejb - september 2006
Ejb  - september 2006Ejb  - september 2006
Ejb - september 2006
achraf_ing
 
09 transactions new1
09 transactions new109 transactions new1
09 transactions new1
thirumuru2012
 
Rollin onj Rubyv3
Rollin onj Rubyv3Rollin onj Rubyv3
Rollin onj Rubyv3
Oracle
 
Java interview-questions-and-answers
Java interview-questions-and-answersJava interview-questions-and-answers
Java interview-questions-and-answers
bestonlinetrainers
 
Hibernate training at HarshithaTechnologySolutions @ Nizampet
Hibernate training at HarshithaTechnologySolutions @ NizampetHibernate training at HarshithaTechnologySolutions @ Nizampet
Hibernate training at HarshithaTechnologySolutions @ Nizampet
Jayarajus
 
Hybernat and structs, spring classes in mumbai
Hybernat and structs, spring classes in mumbaiHybernat and structs, spring classes in mumbai
Hybernat and structs, spring classes in mumbai
Vibrant Technologies & Computers
 
Bea weblogic job_interview_preparation_guide
Bea weblogic job_interview_preparation_guideBea weblogic job_interview_preparation_guide
Bea weblogic job_interview_preparation_guide
Pankaj Singh
 
Design pattern
Design patternDesign pattern
Design pattern
Mallikarjuna G D
 
Technical Interview
Technical InterviewTechnical Interview
Technical Interview
prashant patel
 
Java interview questions
Java interview questionsJava interview questions
Java interview questions
Soba Arjun
 
EJB 3.0 Java Persistence with Oracle TopLink
EJB 3.0 Java Persistence with Oracle TopLinkEJB 3.0 Java Persistence with Oracle TopLink
EJB 3.0 Java Persistence with Oracle TopLink
Bill Lyons
 
Best interview questions
Best interview questionsBest interview questions
Best interview questions
Thesis Scientist Private Limited
 
Core java interview questions
Core java interview questionsCore java interview questions
Core java interview questions
Rohit Singh
 
Jpa
JpaJpa
Technical interview questions
Technical interview questionsTechnical interview questions
Technical interview questions
Soba Arjun
 
Portets to composite applications
Portets to composite applicationsPortets to composite applications
Portets to composite applications
Serge Huber
 

What's hot (16)

Ejb - september 2006
Ejb  - september 2006Ejb  - september 2006
Ejb - september 2006
 
09 transactions new1
09 transactions new109 transactions new1
09 transactions new1
 
Rollin onj Rubyv3
Rollin onj Rubyv3Rollin onj Rubyv3
Rollin onj Rubyv3
 
Java interview-questions-and-answers
Java interview-questions-and-answersJava interview-questions-and-answers
Java interview-questions-and-answers
 
Hibernate training at HarshithaTechnologySolutions @ Nizampet
Hibernate training at HarshithaTechnologySolutions @ NizampetHibernate training at HarshithaTechnologySolutions @ Nizampet
Hibernate training at HarshithaTechnologySolutions @ Nizampet
 
Hybernat and structs, spring classes in mumbai
Hybernat and structs, spring classes in mumbaiHybernat and structs, spring classes in mumbai
Hybernat and structs, spring classes in mumbai
 
Bea weblogic job_interview_preparation_guide
Bea weblogic job_interview_preparation_guideBea weblogic job_interview_preparation_guide
Bea weblogic job_interview_preparation_guide
 
Design pattern
Design patternDesign pattern
Design pattern
 
Technical Interview
Technical InterviewTechnical Interview
Technical Interview
 
Java interview questions
Java interview questionsJava interview questions
Java interview questions
 
EJB 3.0 Java Persistence with Oracle TopLink
EJB 3.0 Java Persistence with Oracle TopLinkEJB 3.0 Java Persistence with Oracle TopLink
EJB 3.0 Java Persistence with Oracle TopLink
 
Best interview questions
Best interview questionsBest interview questions
Best interview questions
 
Core java interview questions
Core java interview questionsCore java interview questions
Core java interview questions
 
Jpa
JpaJpa
Jpa
 
Technical interview questions
Technical interview questionsTechnical interview questions
Technical interview questions
 
Portets to composite applications
Portets to composite applicationsPortets to composite applications
Portets to composite applications
 

Similar to Java Hibernate Basics

Java Spring
Java SpringJava Spring
Java Spring
AathikaJava
 
Spring intro classes-in-mumbai
Spring intro classes-in-mumbaiSpring intro classes-in-mumbai
Spring intro classes-in-mumbai
vibrantuser
 
Hibernate
HibernateHibernate
Hibernate
VISHAL DONGA
 
Spring
SpringSpring
Hibernate - Part 1
Hibernate - Part 1Hibernate - Part 1
Hibernate - Part 1
Hitesh-Java
 
Spring introduction
Spring introductionSpring introduction
Spring introduction
Manav Prasad
 
What is Hibernate Framework?
What is Hibernate Framework?What is Hibernate Framework?
What is Hibernate Framework?
Ducat India
 
Managing Data in Jakarta EE Applications
Managing Data in Jakarta EE ApplicationsManaging Data in Jakarta EE Applications
Managing Data in Jakarta EE Applications
Buhake Sindi
 
What is hibernate?
What is hibernate?What is hibernate?
What is hibernate?
kanchanmahajan23
 
Spring
SpringSpring
Spring
Suman Behara
 
Hibernate - Part 2
Hibernate - Part 2 Hibernate - Part 2
Hibernate - Part 2
Hitesh-Java
 
Session 39 - Hibernate - Part 1
Session 39 - Hibernate - Part 1Session 39 - Hibernate - Part 1
Session 39 - Hibernate - Part 1
PawanMM
 
Session 40 - Hibernate - Part 2
Session 40 - Hibernate - Part 2Session 40 - Hibernate - Part 2
Session 40 - Hibernate - Part 2
PawanMM
 
J2EE Batch Processing
J2EE Batch ProcessingJ2EE Batch Processing
J2EE Batch Processing
Chris Adkin
 
Hibernate
HibernateHibernate
What is hibernate?
What is hibernate?What is hibernate?
What is hibernate?
kanchanmahajan23
 
Introduction to Spring & Spring BootFramework
Introduction to Spring  & Spring BootFrameworkIntroduction to Spring  & Spring BootFramework
Introduction to Spring & Spring BootFramework
Kongu Engineering College, Perundurai, Erode
 
Django è pronto per l'Enterprise
Django è pronto per l'EnterpriseDjango è pronto per l'Enterprise
Django è pronto per l'Enterprise
PyCon Italia
 
Hibernate Interview Questions and Answers
Hibernate Interview Questions and AnswersHibernate Interview Questions and Answers
Hibernate Interview Questions and Answers
AnuragMourya8
 
EJB 3.0 - Yet Another Introduction
EJB 3.0 - Yet Another IntroductionEJB 3.0 - Yet Another Introduction
EJB 3.0 - Yet Another Introduction
Kelum Senanayake
 

Similar to Java Hibernate Basics (20)

Java Spring
Java SpringJava Spring
Java Spring
 
Spring intro classes-in-mumbai
Spring intro classes-in-mumbaiSpring intro classes-in-mumbai
Spring intro classes-in-mumbai
 
Hibernate
HibernateHibernate
Hibernate
 
Spring
SpringSpring
Spring
 
Hibernate - Part 1
Hibernate - Part 1Hibernate - Part 1
Hibernate - Part 1
 
Spring introduction
Spring introductionSpring introduction
Spring introduction
 
What is Hibernate Framework?
What is Hibernate Framework?What is Hibernate Framework?
What is Hibernate Framework?
 
Managing Data in Jakarta EE Applications
Managing Data in Jakarta EE ApplicationsManaging Data in Jakarta EE Applications
Managing Data in Jakarta EE Applications
 
What is hibernate?
What is hibernate?What is hibernate?
What is hibernate?
 
Spring
SpringSpring
Spring
 
Hibernate - Part 2
Hibernate - Part 2 Hibernate - Part 2
Hibernate - Part 2
 
Session 39 - Hibernate - Part 1
Session 39 - Hibernate - Part 1Session 39 - Hibernate - Part 1
Session 39 - Hibernate - Part 1
 
Session 40 - Hibernate - Part 2
Session 40 - Hibernate - Part 2Session 40 - Hibernate - Part 2
Session 40 - Hibernate - Part 2
 
J2EE Batch Processing
J2EE Batch ProcessingJ2EE Batch Processing
J2EE Batch Processing
 
Hibernate
HibernateHibernate
Hibernate
 
What is hibernate?
What is hibernate?What is hibernate?
What is hibernate?
 
Introduction to Spring & Spring BootFramework
Introduction to Spring  & Spring BootFrameworkIntroduction to Spring  & Spring BootFramework
Introduction to Spring & Spring BootFramework
 
Django è pronto per l'Enterprise
Django è pronto per l'EnterpriseDjango è pronto per l'Enterprise
Django è pronto per l'Enterprise
 
Hibernate Interview Questions and Answers
Hibernate Interview Questions and AnswersHibernate Interview Questions and Answers
Hibernate Interview Questions and Answers
 
EJB 3.0 - Yet Another Introduction
EJB 3.0 - Yet Another IntroductionEJB 3.0 - Yet Another Introduction
EJB 3.0 - Yet Another Introduction
 

More from DeeptiJava

Generating the Server Response: HTTP Status Codes
Generating the Server Response: HTTP Status CodesGenerating the Server Response: HTTP Status Codes
Generating the Server Response: HTTP Status Codes
DeeptiJava
 
Java Generics
Java GenericsJava Generics
Java Generics
DeeptiJava
 
Java Collection
Java CollectionJava Collection
Java Collection
DeeptiJava
 
Java Exception Handling
Java Exception HandlingJava Exception Handling
Java Exception Handling
DeeptiJava
 
Java OOPs
Java OOPs Java OOPs
Java OOPs
DeeptiJava
 
Java Access Specifier
Java Access SpecifierJava Access Specifier
Java Access Specifier
DeeptiJava
 
Java JDBC
Java JDBCJava JDBC
Java JDBC
DeeptiJava
 
Java Thread
Java ThreadJava Thread
Java Thread
DeeptiJava
 
Java Inner Class
Java Inner ClassJava Inner Class
Java Inner Class
DeeptiJava
 
JSP Part 2
JSP Part 2JSP Part 2
JSP Part 2
DeeptiJava
 
JSP Part 1
JSP Part 1JSP Part 1
JSP Part 1
DeeptiJava
 
Java I/O
Java I/OJava I/O
Java I/O
DeeptiJava
 
Introduction to Java
Introduction to JavaIntroduction to Java
Introduction to Java
DeeptiJava
 

More from DeeptiJava (13)

Generating the Server Response: HTTP Status Codes
Generating the Server Response: HTTP Status CodesGenerating the Server Response: HTTP Status Codes
Generating the Server Response: HTTP Status Codes
 
Java Generics
Java GenericsJava Generics
Java Generics
 
Java Collection
Java CollectionJava Collection
Java Collection
 
Java Exception Handling
Java Exception HandlingJava Exception Handling
Java Exception Handling
 
Java OOPs
Java OOPs Java OOPs
Java OOPs
 
Java Access Specifier
Java Access SpecifierJava Access Specifier
Java Access Specifier
 
Java JDBC
Java JDBCJava JDBC
Java JDBC
 
Java Thread
Java ThreadJava Thread
Java Thread
 
Java Inner Class
Java Inner ClassJava Inner Class
Java Inner Class
 
JSP Part 2
JSP Part 2JSP Part 2
JSP Part 2
 
JSP Part 1
JSP Part 1JSP Part 1
JSP Part 1
 
Java I/O
Java I/OJava I/O
Java I/O
 
Introduction to Java
Introduction to JavaIntroduction to Java
Introduction to Java
 

Recently uploaded

Infrastructure Challenges in Scaling RAG with Custom AI models
Infrastructure Challenges in Scaling RAG with Custom AI modelsInfrastructure Challenges in Scaling RAG with Custom AI models
Infrastructure Challenges in Scaling RAG with Custom AI models
Zilliz
 
GraphSummit Singapore | Neo4j Product Vision & Roadmap - Q2 2024
GraphSummit Singapore | Neo4j Product Vision & Roadmap - Q2 2024GraphSummit Singapore | Neo4j Product Vision & Roadmap - Q2 2024
GraphSummit Singapore | Neo4j Product Vision & Roadmap - Q2 2024
Neo4j
 
“I’m still / I’m still / Chaining from the Block”
“I’m still / I’m still / Chaining from the Block”“I’m still / I’m still / Chaining from the Block”
“I’m still / I’m still / Chaining from the Block”
Claudio Di Ciccio
 
20240609 QFM020 Irresponsible AI Reading List May 2024
20240609 QFM020 Irresponsible AI Reading List May 202420240609 QFM020 Irresponsible AI Reading List May 2024
20240609 QFM020 Irresponsible AI Reading List May 2024
Matthew Sinclair
 
Removing Uninteresting Bytes in Software Fuzzing
Removing Uninteresting Bytes in Software FuzzingRemoving Uninteresting Bytes in Software Fuzzing
Removing Uninteresting Bytes in Software Fuzzing
Aftab Hussain
 
Video Streaming: Then, Now, and in the Future
Video Streaming: Then, Now, and in the FutureVideo Streaming: Then, Now, and in the Future
Video Streaming: Then, Now, and in the Future
Alpen-Adria-Universität
 
GenAI Pilot Implementation in the organizations
GenAI Pilot Implementation in the organizationsGenAI Pilot Implementation in the organizations
GenAI Pilot Implementation in the organizations
kumardaparthi1024
 
National Security Agency - NSA mobile device best practices
National Security Agency - NSA mobile device best practicesNational Security Agency - NSA mobile device best practices
National Security Agency - NSA mobile device best practices
Quotidiano Piemontese
 
Serial Arm Control in Real Time Presentation
Serial Arm Control in Real Time PresentationSerial Arm Control in Real Time Presentation
Serial Arm Control in Real Time Presentation
tolgahangng
 
Cosa hanno in comune un mattoncino Lego e la backdoor XZ?
Cosa hanno in comune un mattoncino Lego e la backdoor XZ?Cosa hanno in comune un mattoncino Lego e la backdoor XZ?
Cosa hanno in comune un mattoncino Lego e la backdoor XZ?
Speck&Tech
 
Let's Integrate MuleSoft RPA, COMPOSER, APM with AWS IDP along with Slack
Let's Integrate MuleSoft RPA, COMPOSER, APM with AWS IDP along with SlackLet's Integrate MuleSoft RPA, COMPOSER, APM with AWS IDP along with Slack
Let's Integrate MuleSoft RPA, COMPOSER, APM with AWS IDP along with Slack
shyamraj55
 
UiPath Test Automation using UiPath Test Suite series, part 5
UiPath Test Automation using UiPath Test Suite series, part 5UiPath Test Automation using UiPath Test Suite series, part 5
UiPath Test Automation using UiPath Test Suite series, part 5
DianaGray10
 
Goodbye Windows 11: Make Way for Nitrux Linux 3.5.0!
Goodbye Windows 11: Make Way for Nitrux Linux 3.5.0!Goodbye Windows 11: Make Way for Nitrux Linux 3.5.0!
Goodbye Windows 11: Make Way for Nitrux Linux 3.5.0!
SOFTTECHHUB
 
AI 101: An Introduction to the Basics and Impact of Artificial Intelligence
AI 101: An Introduction to the Basics and Impact of Artificial IntelligenceAI 101: An Introduction to the Basics and Impact of Artificial Intelligence
AI 101: An Introduction to the Basics and Impact of Artificial Intelligence
IndexBug
 
GraphSummit Singapore | Graphing Success: Revolutionising Organisational Stru...
GraphSummit Singapore | Graphing Success: Revolutionising Organisational Stru...GraphSummit Singapore | Graphing Success: Revolutionising Organisational Stru...
GraphSummit Singapore | Graphing Success: Revolutionising Organisational Stru...
Neo4j
 
UiPath Test Automation using UiPath Test Suite series, part 6
UiPath Test Automation using UiPath Test Suite series, part 6UiPath Test Automation using UiPath Test Suite series, part 6
UiPath Test Automation using UiPath Test Suite series, part 6
DianaGray10
 
Microsoft - Power Platform_G.Aspiotis.pdf
Microsoft - Power Platform_G.Aspiotis.pdfMicrosoft - Power Platform_G.Aspiotis.pdf
Microsoft - Power Platform_G.Aspiotis.pdf
Uni Systems S.M.S.A.
 
Pushing the limits of ePRTC: 100ns holdover for 100 days
Pushing the limits of ePRTC: 100ns holdover for 100 daysPushing the limits of ePRTC: 100ns holdover for 100 days
Pushing the limits of ePRTC: 100ns holdover for 100 days
Adtran
 
Presentation of the OECD Artificial Intelligence Review of Germany
Presentation of the OECD Artificial Intelligence Review of GermanyPresentation of the OECD Artificial Intelligence Review of Germany
Presentation of the OECD Artificial Intelligence Review of Germany
innovationoecd
 
Driving Business Innovation: Latest Generative AI Advancements & Success Story
Driving Business Innovation: Latest Generative AI Advancements & Success StoryDriving Business Innovation: Latest Generative AI Advancements & Success Story
Driving Business Innovation: Latest Generative AI Advancements & Success Story
Safe Software
 

Recently uploaded (20)

Infrastructure Challenges in Scaling RAG with Custom AI models
Infrastructure Challenges in Scaling RAG with Custom AI modelsInfrastructure Challenges in Scaling RAG with Custom AI models
Infrastructure Challenges in Scaling RAG with Custom AI models
 
GraphSummit Singapore | Neo4j Product Vision & Roadmap - Q2 2024
GraphSummit Singapore | Neo4j Product Vision & Roadmap - Q2 2024GraphSummit Singapore | Neo4j Product Vision & Roadmap - Q2 2024
GraphSummit Singapore | Neo4j Product Vision & Roadmap - Q2 2024
 
“I’m still / I’m still / Chaining from the Block”
“I’m still / I’m still / Chaining from the Block”“I’m still / I’m still / Chaining from the Block”
“I’m still / I’m still / Chaining from the Block”
 
20240609 QFM020 Irresponsible AI Reading List May 2024
20240609 QFM020 Irresponsible AI Reading List May 202420240609 QFM020 Irresponsible AI Reading List May 2024
20240609 QFM020 Irresponsible AI Reading List May 2024
 
Removing Uninteresting Bytes in Software Fuzzing
Removing Uninteresting Bytes in Software FuzzingRemoving Uninteresting Bytes in Software Fuzzing
Removing Uninteresting Bytes in Software Fuzzing
 
Video Streaming: Then, Now, and in the Future
Video Streaming: Then, Now, and in the FutureVideo Streaming: Then, Now, and in the Future
Video Streaming: Then, Now, and in the Future
 
GenAI Pilot Implementation in the organizations
GenAI Pilot Implementation in the organizationsGenAI Pilot Implementation in the organizations
GenAI Pilot Implementation in the organizations
 
National Security Agency - NSA mobile device best practices
National Security Agency - NSA mobile device best practicesNational Security Agency - NSA mobile device best practices
National Security Agency - NSA mobile device best practices
 
Serial Arm Control in Real Time Presentation
Serial Arm Control in Real Time PresentationSerial Arm Control in Real Time Presentation
Serial Arm Control in Real Time Presentation
 
Cosa hanno in comune un mattoncino Lego e la backdoor XZ?
Cosa hanno in comune un mattoncino Lego e la backdoor XZ?Cosa hanno in comune un mattoncino Lego e la backdoor XZ?
Cosa hanno in comune un mattoncino Lego e la backdoor XZ?
 
Let's Integrate MuleSoft RPA, COMPOSER, APM with AWS IDP along with Slack
Let's Integrate MuleSoft RPA, COMPOSER, APM with AWS IDP along with SlackLet's Integrate MuleSoft RPA, COMPOSER, APM with AWS IDP along with Slack
Let's Integrate MuleSoft RPA, COMPOSER, APM with AWS IDP along with Slack
 
UiPath Test Automation using UiPath Test Suite series, part 5
UiPath Test Automation using UiPath Test Suite series, part 5UiPath Test Automation using UiPath Test Suite series, part 5
UiPath Test Automation using UiPath Test Suite series, part 5
 
Goodbye Windows 11: Make Way for Nitrux Linux 3.5.0!
Goodbye Windows 11: Make Way for Nitrux Linux 3.5.0!Goodbye Windows 11: Make Way for Nitrux Linux 3.5.0!
Goodbye Windows 11: Make Way for Nitrux Linux 3.5.0!
 
AI 101: An Introduction to the Basics and Impact of Artificial Intelligence
AI 101: An Introduction to the Basics and Impact of Artificial IntelligenceAI 101: An Introduction to the Basics and Impact of Artificial Intelligence
AI 101: An Introduction to the Basics and Impact of Artificial Intelligence
 
GraphSummit Singapore | Graphing Success: Revolutionising Organisational Stru...
GraphSummit Singapore | Graphing Success: Revolutionising Organisational Stru...GraphSummit Singapore | Graphing Success: Revolutionising Organisational Stru...
GraphSummit Singapore | Graphing Success: Revolutionising Organisational Stru...
 
UiPath Test Automation using UiPath Test Suite series, part 6
UiPath Test Automation using UiPath Test Suite series, part 6UiPath Test Automation using UiPath Test Suite series, part 6
UiPath Test Automation using UiPath Test Suite series, part 6
 
Microsoft - Power Platform_G.Aspiotis.pdf
Microsoft - Power Platform_G.Aspiotis.pdfMicrosoft - Power Platform_G.Aspiotis.pdf
Microsoft - Power Platform_G.Aspiotis.pdf
 
Pushing the limits of ePRTC: 100ns holdover for 100 days
Pushing the limits of ePRTC: 100ns holdover for 100 daysPushing the limits of ePRTC: 100ns holdover for 100 days
Pushing the limits of ePRTC: 100ns holdover for 100 days
 
Presentation of the OECD Artificial Intelligence Review of Germany
Presentation of the OECD Artificial Intelligence Review of GermanyPresentation of the OECD Artificial Intelligence Review of Germany
Presentation of the OECD Artificial Intelligence Review of Germany
 
Driving Business Innovation: Latest Generative AI Advancements & Success Story
Driving Business Innovation: Latest Generative AI Advancements & Success StoryDriving Business Innovation: Latest Generative AI Advancements & Success Story
Driving Business Innovation: Latest Generative AI Advancements & Success Story
 

Java Hibernate Basics

  • 2. Page 2Classification: Restricted Agenda • Introduction • Architecture • The Persistence Lifecycle • Getting Started • Relationships and Associations • Advanced Mapping Concepts • Hibernate Queries • Hibernate Transactions • Hibernate Extensions
  • 4. Page 4Classification: Restricted Preface • Most of the modern languages have embraced Object Oriented Programming (OOP) approach. • OOP based software architecture promotes separation of concerns such that each component does only what it is supposed to do. • Application development should mostly focus on problems in the application domain, which is the business logic. • A highly scalable architecture is one with the least amount of direct dependence between components. • But most application makes use of relational database to persist data. • Somewhere in the guts of the application a database is being queried and a response is offered. • While the demand for such applications has grown, their creation has not become noticeably simpler.
  • 5. Page 5Classification: Restricted Persistence • Persistence of information is one of the most basic requirements in a software application • Almost all languages provide ways and methods to persist data. • J2EE has supported JDBC for persistence since its beginning. • JDBC has been useful but tends to not allow isolation of business logic and persistence concerns. • Some standardization has occurred - the most successful being the Enterprise JavaBeans (EJB) standard of Java 2 Enterprise Edition (J2EE), which provides for container- and bean-managed persistence of entity bean classes. • Unfortunately, this and other persistence models all suffer to one degree or another from the mismatch between the relational model and the object-oriented model. • In short, database persistence is difficult.
  • 6. Page 6Classification: Restricted Plain Old Java Objects (POJOs) • In our ideal world, it would be trivial to take any Java object and persist it to the database. • Object pojoId = value; • MagicPersistenceSolution magic = MagicPersistenceSolution.getInstance(); • pojo = magic.get(pojoId); • POJO pojo = new POJO(); • MagicPersistenceSolution magic = MagicPersistenceSolution.getInstance(); • magic.save(pojo);
  • 7. Page 7Classification: Restricted JDBC Code to Access Relational Data Impact on an Audience What you say How you SayWhat is seen public static String getMessage (int messageId) throws MessageException { Connection c = null; PreparedStatement p = null; String text = null; try { Class.forName(“com.mysql..jdbc.driver"); c = DriverManager.getConnection( "jdbc:mysql://localhost:3306/sample", “root", “admin"); p = c.prepareStatement( "select * from message"); ResultSet rs = p.executeQuery(); while(rs.next()) { text = rs.getString(1); } return text; } catch (Exception e) { log.log(Level.SEVERE, "Could not acquire message", e); throw new RunTimeException( "Failed to retrieve message from the database.", e); } finally { if (p != null) { try { p.close(); } catch (SQLException e) { log.log(Level.WARNING, "Could not close ostensibly open statement.", e); } } if (c != null) { try { c.close(); } catch (SQLException e) { log.log(Level.WARNING, "Could not close ostensibly open connection.", e); } } } }
  • 8. Page 8Classification: Restricted JDBC as a Persistence Solution • Programming with JDBC requires usage of semantics of the database world. • JDBC code has its own rules and concerns, which are not aligned with the business domain. • Application development should mostly focus on problems in the application domain, which is the business logic. • Writing simple JDBC code may be relatively easy, but for complex issues like caching and clustering, JDBC does not offer anything. • JDBC code makes business logic developer worry about persistence issues. Impact on an Audience What you say How you SayWhat is seen
  • 9. Page 9Classification: Restricted EJB Entity Beans as a Persistence Solution • CMP entity beans require a one-to-one mapping to database tables. • They do not directly support inheritance relationships. • They are (by reputation, at least) slow. • Someone has to determine which bean field maps to which table column. • They require special method names. If these are not followed correctly, they will fail silently. • Entity beans have to reside within a J2EE application server environment— they are a heavyweight solution. • They cannot readily be extracted as "general purpose" components for other applications. • They are not serializable. • They rarely exist as portable components to be dropped into a foreign application—you generally have to roll your own EJB solution. Impact on an Audience What you say How you SayWhat is seen
  • 10. Page 11Classification: Restricted Hibernate • Hibernate is an open source ORM framework that is a pioneer and market leader. • Hibernate provides ORM solution which is compatible with the latest Java Persistence API (JPA) specifications. • Provides transparent persistence, allowing the application to switch between database vendors or even persistence mechanism. • Provides complete separation of concerns between domain business logic and persistence. • No need to implement any hibernate specific interfaces, APIs or extend classes from within the domain objects.
  • 12. Page 13Classification: Restricted Hibernate Architecture • Applications make use of Hibernate through the interfaces which it provides. • Hibernate makes itself accessible to the application at the following levels. • Configuration: Allowing application to configure hibernate. • Persistence: Allowing application to persist its domain object over a session in a transaction. Or to retrieve using queries. • Callback: Allowing application to keep track of hibernate events. • Extension: Allowing application to add UserTypes, IdentifierGenerator.
  • 13. Page 14Classification: Restricted Hibernate Architecture ApplicationLayer Application Domain Objects (POJO) Configuration Layer Persistence Layer (Session, Transaction, Query, SessionFactory) Hibernate Extensions Application Database Callback Layer (Interceptor, Validatable, Lifecycle) Dialect JDBC
  • 14. Page 15Classification: Restricted Hibernate Interfaces • Major interfaces of concern in Hibernate are: • Session • SessionFactory • Configuration • Transaction • Query • Callback • Types • Extension
  • 15. Page 16Classification: Restricted Session Interface • Primary interface used by application when interacting with hibernate. • Found in the package org.hibernate. • Light weight interface that acts as a persistence manager. • It is not thread safe and so should be used one per thread. • Represents one unit of work. In web invocation terms, can be mapped to one client request. • The basic level of object cache in Hibernate.
  • 16. Page 17Classification: Restricted SessionFactory • Acts as Factory to the Session objects. • SessionFactory used across the application. • One SessionFactory per database. • Can provide second level of cache for objects across sessions.
  • 17. Page 18Classification: Restricted Configuration • Used for configuring the Hibernate. • Provides access to the configured SessionFactory.
  • 18. Page 19Classification: Restricted Transaction • An optional API, applications can use its own transaction infrastructure if desired. • Provides abstraction over lower level transaction implementation either via JDBC or JTA.
  • 19. Page 20Classification: Restricted Query • Used for querying database to retrieve objects. • Provides way to set query parameters and limit result size. • Comes with a Criteria interface to filter search.
  • 20. Page 21Classification: Restricted Callback • Allows applications to keep track of the events happening in Hibernate. • Interceptor can be used to react to lifecycle events.
  • 21. Page 22Classification: Restricted Callback • Allows applications to keep track of the events happening in Hibernate. • Interceptor can be used to react to lifecycle events.
  • 22. Page 23Classification: Restricted Types • Hibernate Types map to the java types of the data stored in the database. • UserType and CompositeUserType can be used to add domain specific types to hibernate.
  • 23. Page 24Classification: Restricted Extension • Allows extending hibernate functionalities. • Commonly used extension interfaces are IdentifierGenerator and Dialect.
  • 24. Page 25Classification: Restricted The Persistence Lifecycle
  • 25. Page 26Classification: Restricted Lifecycle of Persistence Objects • The application domain objects (POJO) are the persistent objects. • The persistence object can be in one of the three states: • Transient • Persistent • Detached
  • 26. Page 27Classification: Restricted Lifecycle of Persistent Object Garbage collected Transient Persistent Detached new get() load() find() iterate() evict() close() clear() update() saveOrUpdat e() lock() save() saveOrU pdate() delete()
  • 27. Page 28Classification: Restricted Transient Objects • Any application domain object created using a new() operator is a transient object and as such a plain java object. • Any state in such an object is not associated with any database table row. • If such an object is destroyed without becoming persistent, then no data held by the object is stored in the database. • For an object to move from transient state to persistent state requires a call to save() method of the Persistence Manager.
  • 28. Page 29Classification: Restricted Persistent Objects • An object with its database identifier set is a persistent object. • Persistent object is always part of a session and is transactional. • A persistent object can be created by calling save() on the Persistence Manager. • Persistent object might be an instance retrieved from the database using a query. • Persistent objects participate in transactions and its state is synchronized with the database at the end of transaction.
  • 29. Page 30Classification: Restricted Persistent Objects (contd.) • When transaction is committed, Persistent object is synchronized with the database using INSERT, UPDATE or DELETE. • Persistent object may also be synchronized with database before execution of a query to get latest data from the database into memory.
  • 30. Page 31Classification: Restricted Detached Objects • A domain object is persistent only in the scope of the session in which it was created. • If the session is closed using Session.close() then all persistent objects that are still referenced after close() are in detached state. • They are no longer associated with any transaction and will not be synchronized with the database. • The data contained in such objects may not be the latest.
  • 31. Page 32Classification: Restricted Lifecycle of Persistent Object Garbage collected Transient Persistent Detached new get() load() find() iterate() evict() close() clear() update() saveOrUpdat e() lock() save() saveOrU pdate() delete()
  • 32. Page 33Classification: Restricted Object Identity • In Java, objects are often compared for equality using object identity (a==b) • A persistent object may also require comparison of its database identifier, to establish identity. • Concept of transient, persistent and detached objects provides different scopes for objects within which their identities may differ.
  • 33. Page 34Classification: Restricted Object Identity (contd.) • Hibernate supports Transaction-Identity scope. • If a persistent object is accessed multiple times within a same transaction, then hibernate ensures that the same instance is always returned. • This ensures that within a transaction, application works on the same data. • Once a transaction is committed and a session is closed, the resulting detached object is no longer in the transactional scope.
  • 34. Page 35Classification: Restricted Object Identity (contd.) • Equality between to persistent objects can be best established by proper implementation of equals() method in the domain class. • Typical implementation of equals() method will be as follows:- public class Person { public boolean equals(Object other) { if(this == other){ return true; } if(id == null){ return false; } if(!(other instanceof Person)){ return false; } Person person = (Person) other; return this.id.equals(person.getId()); } }
  • 36. Page 37Classification: Restricted Hello World • Create a table called ‘message’: CREATE TABLE message ( message_id INTEGER UNSIGNED NOT NULL AUTO_INCREMENT, text VARCHAR(50) NULL, PRIMARY KEY(message_id) );
  • 37. Page 38Classification: Restricted Hello World • Create a domain class called ‘Message’: package com.csc.training.sample.model; public class Message { private Long id; private String message; public Message(){} public Message(String message){ this.message = message; } public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getMessage() { return message; } public String setMessage(String message) { return this.message = message; } }
  • 38. Page 39Classification: Restricted Hello World • Create a class and property mapping file called ‘Message.hbm.xml’ and place it in the classpath: <?xml version="1.0" encoding="UTF-8"?> <!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.csc.training.sample.model.Message" table="message"> <id name="id" column="message_id"> <generator class="increment"/> </id> <property name="message" column="text"/> </class> </hibernate-mapping>
  • 39. Page 40Classification: Restricted Hello World • Create a Data Access Object (DAO) class called ‘MessageDAO’: package com.csc.training.sample.dao; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.Transaction; import org.hibernate.cfg.Configuration; import com.csc.training.sample.model.Message; public class MessageDAO { public void createMessage(String msg){ Session session = getSessionFactory().openSession(); Transaction tx = session.beginTransaction(); Message message = new Message(msg); session.save(message); tx.commit(); session.close(); } private SessionFactory getSessionFactory() { Configuration configuration = new Configuration(); configuration.addResource("com/csc/training/sample/model/Message.hbm.xml"); return configuration.buildSessionFactory(); } }
  • 40. Page 41Classification: Restricted Hello World • Create a Test class of the DAO called ‘MessageDAOTest’: package com.csc.training.sample.dao; public class MessageDAOTest { public static void main(String[] args){ MessageDAO dao = new MessageDAO(); dao.createMessage("Hello World"); } }
  • 41. Page 42Classification: Restricted Hello World • Create the configuration file called ‘hibernate.properties’: hibernate.connection.driver_class=com.mysql.jdbc.Driver hibernate.connection.url=jdbc:mysql://localhost:3306/sample hibernate.connection.username=root hibernate.connection.password=admin hibernate.dialect=org.hibernate.dialect.MySQLInnoDBDialect
  • 42. Page 43Classification: Restricted Hello World • Add following jars to classpath: • antlr-2.7.6.jar • asm.jar • cglib-2.1.3.jar • commons-collections.jar • commons-logging-1.1.jar • dom4j-1.6.1.jar • hibernate3.jar • jta.jar • mysql-connector-java-3.0.9-stable-bin.jar • oscache-2.3.2.jar
  • 43. Page 44Classification: Restricted Hello World • Run the app with main method in the MessageDAOTest class. • The data should be inserted in the database.
  • 44. Page 45Classification: Restricted Hibernate Relationships and Associations
  • 45. Page 46Classification: Restricted Data relationships • Most of the data found in application domain are related to each other. • Relational databases are efficient in mapping these relations using foreign keys. • Using Hibernate to map to such data from the object model requires special consideration. • The types of relations typically observed in the relational database world are: • One-to-One relationship • One-to-Many relationship • Many-to-One relationship • Many-to-Many relationship
  • 46. Page 47Classification: Restricted Object associations • In the world of OOP the relations between entities are more commonly implemented using associations that can be: • Composition • Inheritance
  • 47. Page 48Classification: Restricted One-to-One relations using foreign key • The relational data can have a one-to-one relationship as can be seen between a person and her address.
  • 48. Page 49Classification: Restricted One-to-One relations using foreign key • In this case the domain object model will have a corresponding Person class referencing an Address object as a property. • When a Persistent instance of Person class is loaded, the persistent instance of its referenced Address instance should also be loaded appropriately. • To enable this, the two classes should be mapped appropriately.
  • 49. Page 50Classification: Restricted One-to-One relations using foreign key package com.sample.hibernate.model; public class Person { private int id; private Address billingAddress; private String name; public boolean equals(Object other){ if(this==other)return true; if(id==null) return false; if(!(other instanceof Person)) return false; Person person = (Person) other; return this.id.equals(person.getId()); } } package com.sample.hibernate.model; public class Address { private String lane; private String city; private String state; }
  • 50. Page 51Classification: Restricted One-to-One relations using foreign key • For foreign key association, Hibernate does not distinguish between One- to-One and One-to-many relations and in this case we use the <many- to-one> tag for mapping the one-to-one relation. • In this example, the mapping file for Person class will have the following entry: <many-to-one name="billingAddress" class="com.sample.hibernate.mode.Address" column="Address_id" cascade="save-update"/> Person.hbm.xml
  • 51. Page 52Classification: Restricted One-to-One relations using foreign key (Bi- directional) • In the previous example, there was only one way navigation from Person to Address. • If we would like to go back to Person instance from Address, then there should be a reference to Person in Address class, which will be mapped as follows. <one-to-one name=“person" class="com.sample.hibernate.mode.Person" property-ref=“billingAddress"/> Address.hbm.xml • This will ensure that the Address instance will hold reference to its appropriate Person instance so that bi-directional navigation can be achieved.
  • 52. Page 53Classification: Restricted One-to-One relations using primary key • The one-to-one relation can also be established through primary key association. • The primary key will also act as a foreign key in this case
  • 53. Page 54Classification: Restricted One-to-One relations using primary key • In this case it must be ensured that the newly created Address objects have the same key as the Person for which it is created. • The mappings in this case will be: Person.hbm.xml <one-to-one name="billingAddress" class="com.sample.hibernate.mode.Address" cascade="save-update"/> Address.hbm.xml <one-to-one name=“person" class="com.sample.hibernate.mode.Person" constrained=“true"/> • Constrained attribute tells Hibernate that the Address has a foreign key constraint on its primary key and it refers to the Person primary key.
  • 54. Page 55Classification: Restricted One-to-One relations using primary key • To ensure that newly saved Address instances are assigned the same primary key as that of the person, a special identifier-generator needs to be used. Address.hbm.xml <class name="com.sample.hibernate.mode.Address" table="Address"> <id name="id" column="Person_id" > <generator class="foreign"> <param name="property"> person </param> </generator> </id> • The property “person” of the new Address object is used to get the identifier which is assigned to the Address identifier.
  • 55. Page 56Classification: Restricted One-to-Many relations - Unidirectional • For unidirectional navigation, the item class will hold a collection of bids. • The relationship will be mapped using the <set> element. Item.hbm.xml <set name="bids“ table=“Bid”> <key column="Item_ID"/> <one-to-many class="Bid"/> </set>
  • 56. Page 57Classification: Restricted One-to-Many relations – Bidirectional • For bidirectional navigation, the Bid class will hold the item for which the bid is created. • The item property can be mapped as follows. Bid.hbm.xml <many-to-one name=“item" column="Item_ID“ class=“Item” not-null=“true"/>
  • 57. Page 58Classification: Restricted Many-to-Many relations - Unidirectional • A many to many relation should ideally make use of a link table. • The link table will have foreign keys to the primary keys of the original table.
  • 58. Page 59Classification: Restricted Many-to-Many relations - Unidirectional • The category class in this case will hold reference to the Item in the form of collection of value types. • The link table will have foreign keys to the primary keys of the original table. Category.hbm.xml <set name="items" table="CATEGORY_ITEM" lazy="true" cascade="save-update“> <key column="category_id"/> <many-to-many class="Item" column="Item_ID"/> </set>
  • 59. Page 60Classification: Restricted Many-to-Many relations - Bidirectional • Item class holds reference to categories as well. Item.hbm.xml <set name=“categories" table="CATEGORY_ITEM" lazy="true“ inverse=“true” cascade="save-update" <key column=“Item_ID"/> <many-to-many class=“Category“ column=“Category_ID"/> </set>
  • 61. Page 62Classification: Restricted Hibernate type system • When working with hibernate, we have to deal with two data types: • The data type of the underlying database • The Java data types • The Java types need to be mapped to the data types in the database • In the mapping files, the types are mapped as follows • <property name=“email” column=“EMAIL” type=“string”/>
  • 62. Page 63Classification: Restricted Built-in mapping types  Hibernate comes with in built-in mapping types for various Java and SQL types CHAR(1) (‘T’ or ‘F’)Boolean or java.lang.BooleanTrue_false CHAR(1) (‘Y’ or ‘N’)Boolean or java.lang.BooleanYes_no BITBoolean or java.lang.BooleanBoolean TINYINTByte or java.lang.ByteByte VARCHARJava.lang.StringString CHAR(1)Java.lang.StringCharacter NUMERICJava.math.BigDecimalBig_decimal DOUBLEDouble or java.lang.DoubleDouble SMALLINTShort or java.lang.ShortShort BIGINTLong or java.lang.LongLong INTEGERInt or java.lang.Integerinteger SQL typeJava typeMapping type
  • 63. Page 64Classification: Restricted Built-in mapping types  The built in data type for dates and times are DATEJava.util.CalendarCalendar_date TIMESTAMPJava.util.CalendarCalendar TIMESTAMPJava.util.Date or java.sql.Timestamp Timestamp TIMEJava.util.Date or java.sql.TimeTime DATEJava.util.Date or java.sql.DateDate SQL typeJava typeMapping type
  • 64. Page 65Classification: Restricted Built-in mapping types  The built in data type for large object mappings are BLOBJava.sql.BlobBlob CLOBJava.sql.ClobClob VARBINARY (or BLOB)Any java class that implements Serializable Serializable CLOBJava.lang.StringText VARBINARY (or BLOB)Byte[]Binary SQL typeJava typeMapping type  The java.sql.Blob or java.sql.Clob may be the most efficient way of handling large objects  But these may not be supported by drivers for all databases  If a Blob or Clob is referenced in a persistent class, then they will only be available in a transaction and not when it is in detached state
  • 65. Page 66Classification: Restricted Mapping Inheritance  Inheritance is a very powerful OOP concept and is used quite often in applications  Relational database does not support inheritance. It only establishes relations using foreign keys  For scenarios where the application domain object has an inheritance type of relationship, there are a few things to be considered while creating the mapping.
  • 66. Page 67Classification: Restricted  Consider a case where an application has multiple billing options  Credit card  Bank account  In this case, the user name and details are same, only the type specific details differ CreditCard Type:int expMonth:String expYr:String BankAccount Name:String Swift:string BillingDetails Owner:String number:String Created:Date Mapping Inheritance
  • 67. Page 68Classification: Restricted  One of the strategies that can be applied is Table per concrete class  In this case, the user name and details are same, only the type specific details differ  This is a little inefficient as two queries are needed to fetch the details Table per Concrete Class
  • 68. Page 69Classification: Restricted  Another strategy that can be applied is table per hierarchy  A single table representing all the details  Although there is a single table the classes will still be separate Table per Hierarchy
  • 69. Page 70Classification: Restricted  The mappings for the table per hierarchy will make use of the <subclass> element  This approach requires all properties of credit card and bank details to be nullable. <hibernate-mapping> <class name="BillingDetails“ table="BillingDetails"> <id name="id" column="BillingDetailsId"> <generator class="increment"></generator> </id> <discriminator column=“BILLINGTYPE” /> <subclass name="CreditCard" discriminator-value="CC"> <property name=“ccnumber" column=“number"/> </subclass> <subclass name="BankAc" discriminator-value="Bank"> <property name=“acnumber” column=“number”/> </subclass> </class> </hibernate-mapping> Table per Hierarchy
  • 70. Page 71Classification: Restricted  Another strategy that can be applied is table per subclass  The tables contain only the required columns and a foreign key to the BillingDetails  The foreign key also acts as the primary key of the table Table per Subclass
  • 71. Page 72Classification: Restricted  A <joined-subclass> element is used to indicate table-per subclass mapping <class name="BillingDetails“ table="Billing_Details"> <id name="id" column="id"> <generator class="increment“/> </id> <joined-subclass name="CreditCard" table="CreditCardDetails"> <key column="Billing_Details_Id"/> <property name="cctype" column="cctype"/> </joined-subclass> <joined-subclass name=“BankAc" table=“BankAcDetails"> <key column="Billing_Details_Id"/> <property name=“swift" column=“swift"/> </joined-subclass> </class> Table per Subclass
  • 73. Page 74Classification: Restricted Queries • Queries are most important for writing good data access code • Hibernate provides extensive support for querying using its Query interface • Hibernate uses powerful language Query Language called HQL (Hibernate Query Language) • Queries are in terms of classes and properties and not tables and columns • Hibernate also supports execution of native SQL queries
  • 74. Page 75Classification: Restricted Queries • Queries can be created on a session • Query hqlQuery = session.createQuery(“from Person”); • Queries support pagination by limiting results • Query query = session.createQuery(“from User”); Query.setFirstResult(0); Query.setMaxResults(10);
  • 75. Page 76Classification: Restricted Queries:Example Query query = session.createQuery("from Employees"); query.setFirstResult(1); query.setMaxResults(10); List<Employees> empList = query.list(); for( Employees e:empList) { System.out.println( e ); }
  • 76. Page 77Classification: Restricted Queries • Queries use the Criteria interface for filtering searches based on criteria • Session.createCriteria(Category.class).add(Expression.like(“ name”, “Laptop%”)); • list() method executes the created query and returns the results as a list • List result = session.createQuery(“from User”).list();
  • 77. Page 78Classification: Restricted Queries:Example public static void criteriaTest(Session session) { session.getTransaction().begin(); Criteria criteria = session.createCriteria(Departments.class); criteria.add(Restrictions.eq("departmentName", "Accounting")); List<Departments> departmentList = criteria.list(); for (Departments d : departmentList) { System.out.println(d); } session.getTransaction().commit(); }
  • 78. Page 79Classification: Restricted Named Queries • Named queries help in avoiding HQL queries to be located within Java files. • The queries to be used in an application can be externalized in an XML mapping file. • The desired query can be referred to by the name. • The getNamedQuery() method is used to obtain a Query instance for a named query given its name. • Named queries allow easier optimization of queries. session.getNamedQuery("findItemsByDescription"). setString("description", description).list(); <query name="findItemsByDescription"> <![CDATA[from Item item where item.description like :description]]> </query>
  • 79. Page 80Classification: Restricted Named Queries:Example public static void findDeptByName(Session session) { session.getTransaction().begin(); List<Departments> departmentList = session.getNamedQuery("findDepartmentByName") .setString("deptName", "Accounting").list(); Departments d = departmentList.get(0); System.out.println(d); session.getTransaction().commit(); } departments.hbm.xml <query name="findDepartmentByName"> <![CDATA[from Departments d where d.departmentName = :deptName]]> </query>
  • 80. Page 81Classification: Restricted The Query API  The Query interface of hibernate is used for retrieving the data from database  Criteria interface is for specifying query criteria  Query hquery = session.createQuery()  Criteria crit = session.createCriteria()
  • 81. Page 82Classification: Restricted Binding Parameters  For passing parameters to a query, the following approaches can be used  Named Parameter  Positional Parameter  Named Parameter  Allows you to specify the name of the expected parameter  String query = “from Item where description like :searchString”  In this case “searchString” is the named parameter  Query qu = session.createQuery(query). setString(“searchString”, searchString);
  • 82. Page 83Classification: Restricted Binding Parameters:Example public static void bindingParameter(Session session) { String sql = "from Employees where employeeId = :empID"; session.getTransaction().begin(); Query query = session.createQuery(sql); query.setInteger("empID", 100); Employees e = (Employees) query.uniqueResult(); System.out.println(e); session.getTransaction().commit(); ses
  • 83. Page 84Classification: Restricted  Positional Parameter  Allows you to specify the parameter position using “?” like prepared statements  String query = “from Item item where item.description like ? and item.date > ?”  Query qu = session.createQuery(query).setString(0, searchString).setDate(1,minDate); Binding Parameters  As seen in the above examples, the setString() and setDate() methods were used, Hibernate also allows setting of various other types as well as entity: Session.createQuery(“from item where item.seller = :seller”). setEntity(“seller”, seller);
  • 84. Page 85Classification: Restricted public static void bindingParameter1(Session session) { String sql = "from Employees where departments = :dept"; session.getTransaction().begin(); Query query = session.createQuery(sql); short s =50; query.setEntity("dept",session.get(Departments.class, s ) ); List<Employees> empList = query.list(); for(Employees e:empList) { System.out.println(e ); // System.out.println(e.getDepartments()); } session.getTransaction().commit(); session.close(); } Binding Parameters:Example
  • 85. Page 86Classification: Restricted Ordering query results  For ordering the results obtained from queries, Hibernate provides order by clause  “from User u order by u.username”  “from User u order by u.username desc”  The Criteria API also provides ordering  Session.createCriteria(User.class). addOrder(Order.asc(“lastname”));
  • 86. Page 87Classification: Restricted Association  The hibernate query language supports performing queries on associations  Join can be used to combine data in two (or more) relations  HQL provides four ways of expressing joins  An ordinary join in the from clause  A fetch join in the from clause  An implicit association join  A theta-style join in the where clause
  • 87. Page 88Classification: Restricted  A fetch join can be used to specify that an association should be eagerly fetched from Item item join fetch item.bids where item.description like “%computer%”; Fetch Join  An alias can be to make query less verbose from Item item join fetch item.bids bid where item.description like “%computer%” and bid.amount > 100;  We can do the same thing using the Criteria API session.createCriteria(Item.class). setFetchMode(“bids”, FetchMode.EAGER). add(Expression.like(“description”, “computer”, MatchMode.ANYWHERE). list();
  • 88. Page 89Classification: Restricted Implicit Association  HQL supports multipart property path expressions for two purposes:  Querying components from User u where u.address.city=“city” Session.createCriteria(User.class). add(Expression.eq(“address.city”, ”city”);  Expressing implicit association joins from Bid bid where bid.item.description like ‘%computer%’;  Implicit joins are directed towards only on many-to-one or one-to-one association.  Its available only on HQL
  • 89. Page 90Classification: Restricted Theta Style Join • Theta style joins are to perform joins between two un-associated classes: from User , Category (Cartesian Product) from User user, Category category where user.username = category.createdBy; • This will return an Object[] with 2 elements • Object[0] -> User • Object[1] -> Category
  • 90. Page 91Classification: Restricted Aggregation  The hibernate query language supports performing various aggregation of the results  The supported aggregation functions are  avg(...), sum(...), min(...), max(...)  count(*), count(...), count(distinct ...)  count(all...) Select count(*) from Item Select sum(amount) from Bid
  • 91. Page 92Classification: Restricted Grouping  Any property or alias appearing in an HQL outside the aggregate function can be used for grouping results select u.lastname, count(u) from User u group by u.lastname Here the results will be grouped according the user’s last name.  Grouping can be restricted using the having clause select u.lastname, count(u) from User u group by u.lastname having user.lastname like ‘A%’
  • 92. Page 93Classification: Restricted Sub-queries  In the databases that support sub-selects, Hibernate supports sub-queries  Sub-queries allow a select query to be embedded in another query from User u where 10 < (select count(i) from u.items I where i.successfulBid is not null) This returns all the users who have bid successfully more than 10 times.
  • 93. Page 94Classification: Restricted Native Queries  Hibernate provides support for making use of native SQL queries instead of HQL.  The SQL query results return the entity instance just like hibernate queries.
  • 94. Page 95Classification: Restricted Native Queries  SQL query may return multiple entity instances  SQL query may return multiple instances of same entity  Hibernate needs to distinguish between different entities  Hibernate uses a naming scheme for the result column aliases to correctly map column values to the properties of particular instances
  • 95. Page 96Classification: Restricted Scalar Queries • SQL queries can be used to return a list of scalars String sql = “select * from appuser”; sesssion.createSQLQuery(sql) .addScalar("username", Hibernate.STRING) .addScalar("name", Hibernate.STRING) .list(); • This will return the scalar values as List of Object[]
  • 96. Page 97Classification: Restricted Entity Queries • Hibernate can also allow you to obtain Entity instances using SQL queries • The SQL queries will need to be supplied with the Entity that represents the table String sql = “select * from address”; Session.createSQLQuery(sql).addEntity(Address.class);
  • 97. Page 98Classification: Restricted Handling Associations • When an entity has a many-to-one relation with another, then it is required to return the association or else a column not found error will be returned. • A * notation will return the association String sql = "select * from user"; session.createSQLQuery(sql) .addEntity(User.class) .list();
  • 98. Page 99Classification: Restricted Returning Non-Managed Entities • SQL can be used to return non-managed entities • The entity instances returned may not reflect the latest values over a session String sql = "select lane, city from address where city like ?"; session.createSQLQuery(sql) .setResultTransformer( Transformers.aliasToBean(Address.class)) .setString(0, cityName) .list();
  • 99. Page 100Classification: Restricted Named SQL Query • SQL queries can be written externally and accessed in the code • Named queries allow more flexibility to modify queries <sql-query name="cityQuery"> <return-scalar column="city" type="string"/> <return-scalar column="lane" type="string"/> <![CDATA[ SELECT a.city AS city, a.lane AS lane FROM Address a WHERE a.city LIKE :cityName ]]> </sql-query>
  • 100. Page 101Classification: Restricted Stored Procedure • Hibernate from version 3 introduces support for queries via stored procedures and functions. • The stored procedure/ function must return a resultset as the first out- parameter to be able to work with Hibernate. CREATE OR REPLACE FUNCTION selectAllEmployments RETURN SYS_REFCURSOR AS st_cursor SYS_REFCURSOR; BEGIN OPEN st_cursor FOR SELECT EMPLOYEE, EMPLOYER, STARTDATE, ENDDATE, REGIONCODE, EID, VALUE, CURRENCY FROM EMPLOYMENT; RETURN st_cursor; END;
  • 101. Page 102Classification: Restricted Stored Procedure • To use the stored procedure, map it through a named query <sql-query name="selectAllEmployees_SP" callable="true"> <return alias="emp" class="Employment"> <return-property name="employee" column="EMPLOYEE"/> <return-property name="employer" column="EMPLOYER"/> <return-property name="startDate" column="STARTDATE"/> <return-property name="endDate" column="ENDDATE"/> <return-property name="regionCode" column="REGIONCODE"/> <return-property name="id" column="EID"/> <return-property name="salary"> <return-column name="VALUE"/> <return-column name="CURRENCY"/> </return-property> </return> { ? = call selectAllEmployments() } </sql-query>
  • 102. Page 103Classification: Restricted Custom SQL • Hibernate3 can use custom SQL statements for create, update, and delete operations • The class and collection persisters in Hibernate already contain a set of configuration time generated strings (insertsql, deletesql, updatesql etc) • The mapping tags <sql-insert>, <sql-delete>, and <sql-update> override these strings
  • 103. Page 104Classification: Restricted Custom SQL • The custom SQL script can also invoke a stored procedure if any • <sql-insert callable="true"> {call createUser (?, ?)} </sql-insert> • <sql-delete callable="true"> {? = call deleteUser (?)} </sql-delete> • The positioning of parameters are important and should be as per what Hibernate expects
  • 105. Page 106Classification: Restricted Transaction • Most enterprise applications working with the database systems need to make use of transactions for data integrity • In an application program, the database transactions should be of as short duration as possible • Ideally, the transaction should be in affect when the application is dealing with the database and not when it is interacting with the user
  • 106. Page 107Classification: Restricted Transaction • Java through JDBC and J2EE though JTA have provided powerful support for transactions. • Hibernate acts as a client to the JDBC and JTA transactions, allowing the application to make use of the features while not worrying about the technical complexities.
  • 107. Page 108Classification: Restricted Hibernate Transaction API • The Transaction interface of hibernate provides methods to define the transaction boundaries • The transaction is created on the session • Transaction tx = session.beginTransaction(); • The commit() method makes performs the database commit • tx.commit(); • In case of failure, rollback() method should be used to rollback the changes • tx.rollback();
  • 108. Page 109Classification: Restricted Flushing Hibernate Session • Changes made to persistent object in a session are stored in memory • Session implements transaction write behind whereby the changes are written to database in a transparent manner and to reduce database access • Flushing of state occurs in the following cases • When a transaction is committed • Before a query is executed • When application calls session.flush()
  • 109. Page 110Classification: Restricted Transaction Isolation Levels • The transaction isolation levels attempt to segregate concurrent transactions and their view of the database state • The isolation levels are implemented by the database vendors, either using locking or multi-version concurrency control • Hibernate makes use of the underlying database implementation and does not on its own add any semantics
  • 110. Page 111Classification: Restricted Optimistic locking in application • Most enterprise applications prefer to use optimistic locking • Optimistic locking assumes there won’t be any conflicts and data will not be updated simultaneously • Optimistic locking can be implemented by using Version number or TimeStamp • When using Version, a column should be added to the table and mapped to a property in the POJO class <version name=“version” column=“VERSION” /> • Whenever the object is changed, hibernate will automatically update the version number
  • 111. Page 112Classification: Restricted Optimistic locking in application • When a transaction retrieves an object, its version number is also fetched • While the object is in detached state, if the corresponding record is updated by another transaction, then the version number in the detached object will be older • Any update issued for this detached object will result in failure since the update query will check for the current version in table to be same as the version number in the detached instance, which will fail with StaleObjectStateException
  • 112. Page 113Classification: Restricted Example hibernate.transaction.factory_class net.sf.hibernate.transaction.JDBCTransactionFactory net.sf.hibernate.transaction.JTATransactionFactory hibernate.transaction.manager_lookupclass Vendor specific and you only need to specify the manager lookup class when you're using a transactional cache. net.sf.hibernate.transaction.JbossTransactionManagerLookup net.sf.hibernate.transaction.WeblogicTransactionManagerLookup
  • 113. Page 114Classification: Restricted Conversation To disconnect from the database server, we execute the code: session.disconnect(); At this point, session object is still valid and will be tracking any changes we make to the objects previously loaded to the application through the Session object; When the application gets control back, it will reconnect to the database using the code: session.reconnect();
  • 115. Page 116Classification: Restricted Custom Mapping Types  Hibernate allows creation of custom value types for the application domain  Some of the data in the database may be stored within multiple columns, but in the object model it may be better to represent it as a class  Example, for a multi currency payment system, the data may be stored as
  • 116. Page 117Classification: Restricted Custom Mapping Types  It may be desirable that the amount is always represented in the same currency, say USD in a separate class like MonetaryAmount even though the database has no support for it. public class MonetaryAmount implements Serializable{ private final BigDecimal value; private final Currency currency; public MonetaryAmount(final BigDecimal value, final Currency currency) { this.value = value; this.currency = currency; } public Currency getCurrency() { return currency; } public BigDecimal getValue() { return value; } public boolean equals(Object o){ …… } public int hashCode() { …… } public static MonetoryAmount convert(MonetoryAmount sourceAmount, Currency targetCurrency){…… } }
  • 117. Page 118Classification: Restricted Custom Mapping Type  To implement a custom user type, the type class needs to implement the interface org.hibernate.usertype.UserType public class MonetaryAmountUserType implements UserType { private static final int[] SQL_TYPES = {Types.NUMERIC}; public int[] sqlTypes() { return SQL_TYPES;} public Class retunedClass() { return MonetoryAmount.class;} public boolean equals(Object x, Object y){ if(x == y) return true; if(x == null || y == null) return false; return x.equals(y); } public Object deepCopy(Object value) { return value;} public Object isMutable() { return false;} public Object nullSafeGet(ResultSet resultSet, String[] names, Object owner) throws HibernateException, SQLException{ if(resultSet.wasNull()) return null; BigDecimal valueInUSD = resultSet.getBigDecimal(names[0]); return new MonetoryAmount(valueInUSD, Currency.getInstance(“USD”)); }
  • 118. Page 119Classification: Restricted Custom Mapping Types  To property with the custom type can now be mapped in the class as below <property name=“amount” column=“Amount” type=“com.sample.hibernate.model. MonetaryAmountUserType”/> public Object nullSafeSet(PreparedStatement statement, Object value, int index) throws HibernateException, SQLException{ if(value == null){ statement.setNull(index, Types.NUMERIC); }else{ MonetoryAmount anyCurrency = (MonetoryAmount) value; MonetoryAmount amountInUSD = MonetoryAmount.convert( anyCurrency, Currency.getInstance(“USD”); statement.setBigDecimal(index, amountInUSD.getValue()); } } }
  • 120. Page 121Classification: Restricted Hibernate Cache  One of the benefits of using Hibernate is its ability to cache the instances  Caching of data in entity instances can provide great performance benefits  Hibernate provides configurable caching, where each class can be separately enabled for caching depending on its usage  Hibernate provides caching at multiple levels
  • 121. Page 122Classification: Restricted Session First Level Cache Second Level Cache Cache Strategy Query Cache Cache Provider Hibernate Cache Architecture
  • 122. Page 123Classification: Restricted  The hibernate cache provides caching at two levels  The first level cache is the Session Cache which is enabled by default and can not be disabled  The second level cached can be chosen between  Process Cache – shared between many unit of work (transaction)  Clustered Cache –shared between multiple process on same/multiple systems. Hibernate Cache Architecture
  • 123. Page 124Classification: Restricted First Level Cache  All the persistence instances that are in Persistent state stay in the First Level Cache  Changes made in a unit of work are cached in the first level cache  Changes made to object are written to database only on flush()  You can opt to not keep data in first level cache by using evict() method  Not useful for application that deal with bulk or large quantity of data. In such case, we are better off using plain SQL or stored procedures
  • 124. Page 125Classification: Restricted Second Level Cache  The second level cache is at a higher level and allow data to be shared across the application if opting for Process cache  The cluster cache is across multiple servers and relies on remote communication to synchronize the cache  The second level cache stores data in the form of values  A Class can be enabled for caching by indicating it in the mapping file  Disable second level cache by setting hibernate.cache.use_second_level_cache = false in hibernate.cfg.xml
  • 125. Page 126Classification: Restricted Example To eanable caching include <property name="hibernate.cache.provider_class">org.hibernate.cache.EhCacheProvi der</property> In hibernate.cfg.xml file. Create ehcache.xml file it may be hbm specific or a default one.
  • 126. Page 127Classification: Restricted <ehcache> <diskStore path="java.io.tmpdir"/> <defaultCache maxElementsInMemory="1000“ eternal = true/false timeToIdleSeconds="120" timeToLiveSeconds="120" overflowToDisk="true" /> <cache name="example.survey.Survey" maxElementsInMemory="1000“ eternal = true/false timeToIdleSeconds="3600" overflowToDisk="false" /> </ehcache>
  • 127. Page 128Classification: Restricted <class name="example.survey.Survey“ table="SURVEYS"> <cache usage="read-write"/> <class> Read-Only Cache Usage If your application’s Session object will be loading various classes and the classes don’t and won’t change during the execution of the application, you can use the read-only cache usage. Else read-write
  • 128. Page 129Classification: Restricted Query Cache To enable query cache use hibernate.cache.use_query_cache=”true” in hibernate.cfg.xml Session session = SessionFactory.openSession(); Query query = session.createQuery("from Survey"); query.setCacheable(true); query.setCacheRegion("surveys"); List users = query.list(); SessionFactory.closeSession();
  • 129. Page 130Classification: Restricted Controlling second level cache You can manage the SessionFactory second-level cache using the following methods: public void evict(Class class); public void evict(Class class, Serializable id); public void evictCollection(String name); public void evictCollection(String name, Serializable id); The primary role of each of these methods is to permanently remove objects from the cache.
  • 130. Page 131Classification: Restricted Controlling session cache public void evict(Object object); Clears the object from the cache public void clear(); Clears entire cache. boolean contains(Object object); Returns true/false
  • 131. Page 132Classification: Restricted When not to use caching If your database is being modified by multiple applications, then Hibernate won’t be able to ensure that the data is valid. Some data is retrieved and then not reused so that the data expires from the cache. In this case,there is no point in caching the information and taking up more memory. You’re loading very large numbers of objects. If you’re loading and parsing millions of objects then there may not be enough memory available to cache them.
  • 132. Page 133Classification: Restricted Filters Dynamic data filtering is related to data security. <class name="Item" table="ITEM"> ... <filter name="limitItemsByUserRank" condition=":currentUserRank >= (select u.RANK from USER u where u.USER_ID = SELLER_ID)"/> </class> Filter filter = session.enableFilter("limitItemsByUserRank"); filter.setParameter("currentUserRank", loggedInUser.getRanking());
  • 133. Page 134Classification: Restricted Interceptor • An interceptor can be used to intercept the existing business functionality to provide extensible or add-on features • They provide pluggable architecture and are generally callback methods that will be called by the framework in response to a particular set of events/actions if properly registered and configured. • Example EmptyInterceptor override public boolean onSave(Object entity, Serializable id, Object[] state, String[] propertyNames, Type[] types) throws CallbackException { }
  • 134. Page 135Classification: Restricted And public boolean onFlushDirty(Object entity,Serializable id,Object[] currentState, Object[] previousState, String[] propertyNames, Type[] types) throws CallbackException { }
  • 135. Page 136Classification: Restricted Projection The ability to retrieve only properties of an entity or entities, without the overhead of loading the entity itself into the persistence context. This is sometimes called a report query; it is more correctly called projection. Criteria crit = sess.createCriteria(ClassName.class); ProjectionList proList = Projections.projectionList(); proList.add(Projections.property(“prop1")); proList.add(Projections.property(“prop2")); crit.setProjection(proList); List list = crit.list();
  • 136. Page 137Classification: Restricted N+1 selection problem The following example code tries to find the highest Bids for all Items List<Item> allItems = session.createQuery("from Item").list(); 1 query n rows Map<Item, Bid> highestBids = new HashMap<Item, Bid>(); for (Item item : allItems) { Bid highestBid = null; for (Bid bid : item.getBids() ) { // Initialize the collection 1 qery if (highestBid == null) highestBid = bid; if (bid.getAmount() > highestBid.getAmount()) highestBid = bid; } highestBids.put(item, highestBid); }
  • 137. Page 138Classification: Restricted Solution A first solution could be a change of your global mapping metadata for the collection, enabling prefetching in batches: <set name="bids" inverse="true" batch-size="10"> <key column="ITEM_ID"/> <one-to-many class="Bid"/> </set> •2nd strategy fetch="join“ •fetch="subselect“ one query to find all the items 2nd to fetch all the bids
  • 138. Page 139Classification: Restricted The Cartesian product problem This Cartesian product problem always appears if you try to fetch several “parallel” collections <class name="Item"> ... <set name="bids"inverse="true“ fetch="join"> <key column="ITEM_ID"/> <one-to-many class="Bid"/> </set> <set name="images“ fetch="join"> <key column="ITEM_ID"/> <composite-element class="Image">... </set> </class>
  • 139. Page 140Classification: Restricted select item.*, bid.*, image.* from ITEM item left outer join BID bid on item.ITEM_ID = bid.ITEM_ID left outer join ITEM_IMAGE image on item.ITEM_ID = image.ITEM_ID

Editor's Notes

  1. Narrate the story of Boeing 747 Barriers can be listed as Complexity Jargon Visibility Poor sound Bad listening Prejudice and bias Lack of clarity Level of the audience Timing