SlideShare a Scribd company logo
Hibernate 3.6 
© Onkar Deshpande
Table of Contents 
Module Title Page 
1 Introduction to Hibernate 3 
2 Getting started 13 
3 Hibernate API for CRUD 21 
4 Some mapping clauses 29 
5 More mapping concepts 40 
6 The Association relations 55 
7 Hibernate Transaction Support 64 
8 Queries in Hibernate 82 
9 Advanced queries 92 
10 More on hibernate 102 
© Onkar Deshpande
Module 1. Introduction to Hibernate 
 Overview 
 Database layer tools-Wrappers and ORM 
 What is hibernate? 
 OOPs and RDBMS paradigm mismatch 
 The ORM solutions 
 Hibernate Vs. JPA 
 Hibernate architecture 
© Onkar Deshpande
Database layer tools 
OOPS 
Business Layer 
Service Layer 
Presentation Layer 
JDBC Layer 
JDBC Wrapper 
Spring JDBC 
JPA 
Hibernate 
iBatis 
Database 
© Onkar Deshpande
5 
Hibernate Clients 
Desktop application 
Console/Swing 
Spring 
application 
EJB Container 
Web application 
Struts/WebWork/TabeStray 
Hibernate Database 
© Onkar Deshpande
What is Hibernate? 
 What is hibernate? 
 A powerful ORM tool to design data base access layer. 
 Fills gaps of mismatches between OOPs and RDBMS 
paradigm. Also maintains adequate ultra performance of 
database access. 
 An automated, configurable persistence of java objects with 
tables in data base. 
 May not be a good solution for data-centric application 
which uses only stored procedures to implement business 
logic in the database. 
© Onkar Deshpande
Hibernate versions 
 Hibernate 3.2 
 Most commonly used production version. 
 Full support for JPA 1.0. 
 Hibernate 3.5 
 Full support for JPA 2.0. 
 Hibernate 3.6 
 Full support of JEE 5. 
 Hibernate 4.1 
 Full Support to JEE 6 
 Hibernate 4.3 
 Full Support to JEE 7 
© Onkar Deshpande
Paradigm mismatch 
 Problem of Granularity. 
 Problem of subtypes. 
 Problem of identity. 
 Problems relating to association. 
 Problem of object graph navigation. 
© Onkar Deshpande
The ORM solutions 
 Wrapper for basic CRUD operations. 
 Language or API for specifying queries that refers to 
Objects and their properties. 
 Facility for specifying mapping metadata. 
 Techniques to match the mismatches between OOPs 
and Databases. 
 Dirty checking, lazy fetching, and other optimization 
functions. 
© Onkar Deshpande
Hibernate Vs. JPA 
 JPA is set of specifications of which implementation is 
provided in Toplink, hibernate 3.0 etc. 
 JPA is a standard while hibernate is not. 
 JPA ‘s some of the implementations have been blamed 
as slow. 
 EntityManager and EntityManagerFactory are thin 
wrappers around Session and SessionFactory etc. 
© Onkar Deshpande
Hibernate Architecture 
Overview of Hibernate in layered architecture 
Business Layer 
Persistent Layer 
Persistence 
Classes 
Session Query User Types Interceptors 
Session Factory Configuration Transaction 
© Onkar Deshpande
Hibernate Architecture 
Overview of Hibernate in layered architecture 
Business Layer 
Persistent Layer 
Persistence 
Classes 
Session Query User Types Interceptors 
Session Factory Configuration Transaction 
© Onkar Deshpande
Module 2. Getting started 
 Overview 
 Hibernate Configuration- XML and properties 
 Mapping tables with beans 
 Hibernate SessionFactory and Session 
 Mapping using annotations 
 Object states. 
© Onkar Deshpande
Configuration using XML 
<hibernate-configuration> 
<session-factory> 
<property name="hibernate.connection.driver_class">oracle.jdbc.OracleDriver</property> 
<property name="hibernate.connection.url">jdbc:oracle:thin:@localhost:1521:ORCL</property> 
<property name="hibernate.connection.username">scott</property> 
<property name="hibernate.connection.password">tiger</property> 
<property name="hibernate.connection.pool_size">10</property> 
<property name="show_sql">true</property> 
<property name="hibernate.use_sql_comments">true</property> 
<property name="dialect">org.hibernate.dialect.Oracle9Dialect</property> 
<mapping resource="comhibernatepack10_beginempBean.hbm.xml"/> 
</session-factory> 
</hibernate-configuration> 
© Onkar Deshpande
Mapping tables with beans 
Mapping metadata… 
<hibernate-mapping> 
<class name="com.hibernate.pack10_begin.EmpBean" table="EMP"> 
<id name="empNo" type="int" column="EMPNO" > 
<generator class="native"/> 
</id> 
<property name="ename"> 
<column name="ENAME" /> 
</property> 
<property name="sal"> 
<column name="EMPSAL"/> 
</property> 
</class> 
</hibernate-mapping> 
public class EmpBean { 
private int empNo; 
private String empNm; 
private Float empSal; 
public void setEmpNo(int empNo) { 
this.empNo = empNo; 
} 
public void setEname(String empNm) { 
this.empNm = empNm; 
} 
public void setSal(Float empSal) { 
this.empSal = empSal; 
}} 
© Onkar Deshpande
SessionFactory and Session 
 Booting steps... 
 Create configuration object. 
Configuration config = new Configuration(); 
config.configure(“pack10_beginhibernate_begin.cfg.xml”); 
 Build session factory. 
SessionFactory sessions = config.buildSessionFactory(); 
 Open session 
Session session = sessions.openSession(); 
 Start transaction 
Transaction transaction = session.beginTransaction(); 
 Handle session 
session.save(), session.update() etc. 
 Conclude transaction 
transaction.commit(), transaction.rollback() 
 Close session. 
 session.close() 
© Onkar Deshpande
Mapping using annotations. 
@ Entity 
@ Table (name="emp") 
public class EmpBean { 
private int empNo; 
private String empNm; 
private Float empSal; 
@ Id 
@ Column(name="EMPNO") 
public int getEmpNo() { 
return empNo; 
} 
} 
Configuration in xml… 
<mapping class=“hiber10annot.EmpBean"/> 
© Onkar Deshpande
Object States 
 Transient 
 Persistent 
 Detached 
© Onkar Deshpande
Transient Object states 
JVM 
Database 
Persistence Heap Stack 
Context 
Scott 
21 
1000 
2-01-12 
Reference 
Session 
© Onkar Deshpande
Persistent Object states 
JVM 
Database 
Persistence Heap Stack 
Context 
Scott 
21 
1000 
2-1-12 
Reference 
Session 
Name Age Salary DOJ 
Scott 21 1000 2-1-12 
Reference 
© Onkar Deshpande
Detached Object states 
JVM 
Database 
Persistence Heap Stack 
Context 
Scott 
21 
1000 
2-1-12 
Reference 
Session 
Name Age Salary DOJ 
Scott 21 1000 2-1-12 
Reference 
© Onkar Deshpande
Module 3. Hibernate API for CRUD 
 Overview 
 The CRUD operations using beans 
 The CRUD operations using XML 
 The CRUD operations using Maps 
© Onkar Deshpande
Object Retrieving 
 Navigating object graph 
 Using get()/load() method. 
 Using HQL. 
© Onkar Deshpande
Object Retrieving 
 Using Criteria queries. 
 Using Query by example. 
 Using native queries. 
© Onkar Deshpande
Insert a record 
Inserts a persistent object into table at the time of commit(). Throws exception on violation of 
any constraint at DB. 
save() persist() 
Hibernate specific Standard as per JSR 220. 
Returns auto generated primary key Does not return any value. 
Update a record 
Dirty check is default feature for persistent object. But for transient object, update or merge 
does update at DB side and makes object as persistent. 
update() merge() 
Hibernate specific Standard as per JSR 220. 
Update the record in DB. Makes an 
trans.or detached object persistent. 
Copies content of transient object into persistent 
object. If there is no persistent object in session, it is 
loaded. 
CRUD operations 
© Onkar Deshpande
Delete a record 
Delete a given record from table provided it exists. Otherwise thros exception. Converts 
persistent object into transient state. 
delete() 
Retrieve a record 
Returns persistent object of the given class and given record it. 
get() load() 
Standard as per JSR 220. Hibernate specific 
Returns initialized instance only if record is 
existing. 
Returns proxy assuming instance is existing. 
Returns null if record is missing. Throws exception later if record is missing. 
Use to get instance or to check existence of 
a record. 
Old version. Use to get instance if record 
surely exists. 
CRUD operations 
© Onkar Deshpande
Data formats for CRUD operations 
 Using plain old java objects: Exchanging DB data with 
OOPs paradigm. 
 Using Maps: Facilitate dynamic change in structure of 
data. 
 Using XML: For exchanging DB data with XML data 
source. 
© Onkar Deshpande
Map format for CRUD operations 
Mapping…. 
<class entity-name="message" table="MESSAGES" > 
<id name="id" column="MESSAGE_ID" type="long"> 
<generator class="increment"/> 
</id> 
<property name="text" column="MESSAGE_TEXT" type="string"/> 
<property name="nextMessage" column="NEXT_MESSAGE_ID" type="long"/> 
</class> 
CRUD Operations… 
Map<String, Object> msg3 = new HashMap<String, Object>(); 
msg3.put("id", 1l); 
msg3.put("text", "Meeting canceled."); 
session.persist(msg3); 
© Onkar Deshpande
Xml format for CRUD operations 
Mapping…. 
<class entity-name="employee" table="Emp" node="employee"> 
<id name="empId" type="int" column="EMPNO" node="empId"> 
<generator class="native"/> 
</id> 
<property name="name" type="string" node="name"> 
<column name="ENAME"/> 
</property> 
<property name="salary" type="float" node="salary"> 
<column name="SAL"/> 
</property> 
</class> 
CRUD Operations… 
Session dom4jSession = session.getSession(EntityMode.DOM4J); 
Element emp = (Element)dom4jSession.load("Employee", 7499); 
System.out.print(emp.elementText("empId")); 
System.out.print("t" + emp.elementText("name")); 
System.out.println("t" + emp.elementText("salary")); 
© Onkar Deshpande
Module 4. Some mapping clauses 
 Overview 
 The paradigm mismatch- OOPs Vs. RDBMS 
 Hibernate built-in data types 
 Bypassing properties 
 Formula field 
 Making field-class immutable 
 Making field not-null 
 The object identity 
 Key auto-generation 
 Composite keys. 
© Onkar Deshpande
Built-in mapping types. 
Mapping type Java type Standard SQL type 
integer int or java.lang.integer INTEGER 
long long. Or java.lang.Long BIGINT 
short short or java.lang.Short SMALLINT 
float float or java.lang.Float FLOAT 
double double or java.lang.Double DOUBLE 
big-decimal java.math.BigDecimal NUMERIC 
character java.lang.String CHAR 
string java.lang.String VARCHAR 
byte byte or java.lang.Byte TINYINT 
boolean boolean or java.lang.Boolean BIT 
yes_no boolean or java.lang.Boolean CHAR(1) 
true_false boolean or java.lang.Boolean CHAR(1) 
© Onkar Deshpande
Built-in mapping types. 
Mapping type Java type Standard SQL type 
date java.util.Date or java.sql.Date DATE 
time java.util.Date or java.sql.Time TIME 
timeStamp java.util.Date or java.sql.TimeStamp TIMESTAMP 
calendar java.util.Calendar TIMESTAMP 
calendar_date java.util.Calendar DATE 
binary byte[] VARBINAR OR BLOB 
text java.lang.String CLOB 
Serializable Any serializable class VARBINAR OR BLOB 
Clob java.sql.Clob CLOB 
blob java.sql.Blob BLOB 
© Onkar Deshpande
Mapping metadata 
Mapping… 
<class name="com.hibernate.pack50_moremappings.Emp" table="EMP" mutable="true" 
dynamic-update="true"> 
<id name="empNo" column="EMPNO" access="field"> 
<generator class="assigned"/> 
</id> 
<property name="eName" column="ENAME" access="field" not-null="true" /> 
<property name="sal" column="SAL" access="field" /> 
<property name="job" column="JOB" access="field" /> 
<property name="comm" column="COMM" access="field" /> 
<property name="deptNo" column="DEPTNO" access="field" /> 
<property name="totalSal" type="float" formula="SAL+COMM"/> 
</class> 
© Onkar Deshpande
Mapping metadata 
<class name=“pack50_moremappings.Emp" table="EMP“ > 
<id name="empNo" column="EMPNO" > 
<generator class="assigned"/> 
</id> 
<property name="eName" column="ENAME" access="field" not-null="true" /> 
<property name="sal" column="SAL" insert="false" update="false"/> 
<property name="job" column="JOB" /> 
<property name="comm" column="COMM" /> 
<property name="totalSal" type="float“ formula="SAL + COMM" /> 
</class> 
© Onkar Deshpande
Mapping metadata (Contd...) 
 Bypassing setter method for populating field with value. 
 <property name="eName" access="field“/> <!-- default is 
access=“property”-> 
 Accessing derived properties. 
 <property name="totalSal" type="float“ formula="SAL + COMM" /> 
 Avoiding trip to database if not-null field value is null. 
 <property name=" eName” not-null=“true” /> 
 Controlling insertion and updation of a field. 
 <property name="sal" column="SAL" insert="false" update="false"/> 
© Onkar Deshpande
Mapping metadata 
 Importing package for all beans. 
 <hibernate-mapping package=“pack50_moremappings”> 
 Making a class immutable 
 <class name=“Emp" table="EMP" mutable=“false”> 
 To prevent unmodified property value in SQL-insert. 
 <class name=“Emp" table="EMP" dynamic-insert="true”/> 
 To prevent unmodified property value in SQL-update 
 <class name=“Emp" table="EMP" dynamic-update="true”/> 
© Onkar Deshpande
Identifier generators 
Generator Description 
native Picks active identity generators depending upon the database. 
increment Hibernates auto-generation policy. 
assigned User given key value. 
identity Supports identity column. 
sequence Uses sequence policy of data base. 
hilo Uses high/low algorithm policy of data base. 
Declaration in mapping file… 
<id name="empNo" column="EMPNO" type="integer"> 
<generator class="increment"/> 
</id> 
© Onkar Deshpande
Declaration in mapping file… 
<class name="Books" table="Books"> 
<composite-id name="compoKey" class="CompositeId"> 
<key-property name="bookId"> 
<column name="BookId" not-null="true" /> 
</key-property> 
<key-property name="titleId"> 
<column name="TitleId" not-null="true" /> 
</key-property> 
</composite-id> 
<property name="cost" /> 
</class> 
public static class CompositeId implements Serializable 
{ 
private int bookId; 
private String titleId; 
public CompositeIdBooks(){} 
public String getTitleId() { …} 
public void setTitleId(String titleId) { … } 
public int getBookId() {… } 
public void setBookId(int bookId) { …} 
} 
Composite key 
The composite key Embedable 
© Onkar Deshpande
Composite key (Contd...) 
The entity bean 
@ Entity 
public class Books { 
@Id 
@ EmbeddedId 
private CompositeIdBooks compoKey; 
private float cost; 
public Books(CompositeIdBooks compoKey, float cost){ 
this.compoKey = compoKey; 
this.cost = cost; 
} 
} 
Accessing entity using composite key… 
Books.CompositeIdBooks bookKey1 = new Books.CompositeIdBooks(3, "AB124"); 
Books book1 = new Books(bookKey1, 1236.00f); 
session.save(book1); 
© Onkar Deshpande
Key equality. 
 Emp emp2 = (Emp) session.load( Emp.class, 7499 ); 
 Emp emp3 = (Emp) session.load( Emp.class, 7499 ); 
System.out.println("Returning cached 
object:"+emp2.hashCode()+" "+emp3.hashCode()); 
 System.out.println(session.getIdentifier(emp2)); 
 System.out.println(session.getIdentifier(emp3)); 
© Onkar Deshpande
Module 5. More mapping concepts 
 Overview 
 The paradigm mismatch- Granularity OOPs Vs. RDBMS 
 Matching fine-granularity 
 Matching objects’ inheritance structure with tables 
 Mapping collections of value type 
© Onkar Deshpande
Granularity matching 
public class User { 
private int userId; 
private String userName; 
private Address billingAddress; 
private Address homeAddress; 
…………. 
} 
public class Address { 
private String street; 
private String city; 
private String pin; 
private User user; 
…………… 
} 
Table structure: 
USER_ID number(5) not null, 
USERNAME varchar2(15) not null, 
HOME_STREET varchar2(10), 
HOME_CITY varchar2(10), 
HOME_PIN varchar2(6), 
BILLING_STREET varchar2(10), 
BILLING_CITY varchar2(10), 
BILLING_PIN varchar2(6) 
© Onkar Deshpande
Granularity matching (Contd...) 
Mapping… 
<class name="User" table="USERS"> 
<id name="id" column="USER_ID" type="integer"> 
<generator class="native"/> 
</id> 
<property name="userName" column="USERNAME" /> 
<component name="homeAddress" class="Address"> 
<parent name="user"/> // For bi-directional navigation. 
<property name="street“ column="HOME_STREET" /> 
<property name="city" column="HOME_CITY" /> 
<property name="pin“ column="HOME_PIN" /> 
</component> 
…… 
</class> 
Loading of object… 
User user = (User) session.load( User.class, 1 ); 
Navigation from User to Address to user: 
user.getBillingAddress().getUser().getUserName()); 
© Onkar Deshpande
Mapping inheritance 
 Approaches to represent inheritance hierarchy… 
 Table per concrete class : Discards inheritance hierarchy and 
polymorphism 
 Table per class hierarchy: Enable polymorphism by de-normalizing 
relational model. 
 Table per sub class: Represents inheritance as a foreign key 
relationship. 
© Onkar Deshpande
The inheritance hierarchy 
BankAccount 
-accNo : int 
-accNM : String 
-accBal : float 
SavingsAcc 
-isSalAcc : boolean 
CurrentAcc 
-crLimit : float 
© Onkar Deshpande
Table per 
concrete class. 
BankAcc 
SavingsAcc CurrentAcc 
Table: CCSavings 
ACCNO number(4), 
ACC_NM varchar2(15), 
ACC_BAL number(8,2), 
IS_SALACC number(1), 
CONSTRAINT pk_accno_ccsavings PRIMARY KEY (ACCNO) 
Table: CCCurrent 
ACCNO number(4), 
ACC_NM varchar2(15), 
ACC_BAL number(8,2), 
CR_LIMIT number(8), 
CONSTRAINT pk_accno_cccurrent PRIMARY KEY (ACCNO) 
<class name="SavingsAcc" table="CCSavings"> 
<id name="accNo" column="ACCNO" type="integer"> 
…… 
<property name="accNm" column="ACC_NM" type="string" /> 
……. 
</class> 
<class name="CurrentAcc" table="CCCurrent"> 
<id name="accNo" column="ACCNO" type="integer"> 
…… 
<property name="accNm" column="ACC_NM" type="string" /> 
……. 
</class> 
© Onkar Deshpande
One table with 
discriminator. 
BankAcc 
SavingsAcc CurrentAcc 
Table: CHAccounts 
ACCNO number(4), 
ACC_NM varchar2(15), 
ACC_BAL number(8,2), 
ACCTYPE varchar2(2), 
IS_SALACC number(1), 
CR_LIMIT number(8) 
CONSTRAINT pk_accno_CHAccounts PRIMARY KEY (ACCNO) 
<class name=“BankAcc" table="CHAccounts"> 
<id name="accNo" column="ACCNO" type="integer"> 
…… 
<discriminator column="ACCTYPE" type="string" not-null="true"/> 
<property name="accNm" column="ACC_NM" type="string" /> 
……. 
<subclass name="SavingsAcc" discriminator-value="SA"> 
<property name="salAcc" column="IS_SALACC" type="boolean“/> 
</subclass> 
<subclass name="CurrentAcc" discriminator-value="CA"> 
<property name="crLimit" column = "CR_LIMIT" type="long”/> 
</subclass> 
© Onkar Deshpande
Table with part 
Joins 
BankAcc 
SavingsAcc CurrentAcc 
Table: PJAccounts 
ACCNO number(4), 
ACC_NM varchar2(15), 
ACC_BAL number(8,2), 
ACCTYPE varchar2(2), 
IS_SALACC number(1), 
CONSTRAINT pk_accno_PJAccounts PRIMARY KEY (ACCNO) 
Table: PJCurrent 
CACCNO number(4), 
CR_LIMIT number(8), 
CONSTRAINT fk_bankAcc_pjcurrent FOREIGN KEY 
(CACCNO) REFERENCES PJAccounts(ACCNO) 
<class name=“BankAcc" table=“PJAccounts"> 
<id name="accNo" column="ACCNO" type="integer"> 
…… 
<discriminator column="ACCTYPE" type="string"/> 
<property name="accNm" column="ACC_NM" type="string" /> 
……. 
<subclass name="SavingsAcc" discriminator-value="SA"> 
<property name="salAcc" column="IS_SALACC" type="boolean“/> 
</subclass> 
<subclass name="CurrentAcc" discriminator-value="CA"> 
<join table="PJCurrent"> 
<key column="CACCNO"></key> 
<property name="crLimit" column = "CR_LIMIT" type="long“/> 
</join> 
</subclass> 
….. 
© Onkar Deshpande
Table with 
subclass joins 
BankAcc 
Table: SCCurrent 
CACCNO number(4), 
CR_LIMIT number(8), 
CONSTRAINT fk_bankAcc_Sccurrent 
FOREIGN KEY (CACCNO) 
REFERENCES SCAccounts(ACCNO) 
SavingsAcc CurrentAcc 
Table: SCAccounts 
ACCNO number(4), 
ACC_NM varchar2(15), 
ACC_BAL number(8,2), 
CONSTRAINT pk_accno PRIMARY KEY (ACCNO) 
Table: SCSavings 
SACCNO number(4), 
IS_SALACC number(1), 
CONSTRAINT fk_bankAcc_Scsaving 
FOREIGN KEY (SACCNO) 
REFERENCES SCAccounts(ACCNO) 
<class name="SavingsAcc" table="CCSavings"> 
<id name="accNo" column="ACCNO" type="integer"> 
…… 
<property name="accNm" column="ACC_NM" type="string" /> 
……. 
<joined-subclass name="SavingsAcc" table="SCSavings"> 
<key column="SACCNO“/> // Primary / Foreign key. 
<property name="salAcc" column="IS_SALACC" type="boolean“/> 
</joined-subclass> 
<joined-subclass name="CurrentAcc" table="SCCurrent"> 
<key column="CACCNO“/> // Primary / Foreign key. 
<property name="crLimit" column = "CR_LIMIT" type="long“/> 
</joined-subclass> 
…… 
© Onkar Deshpande
ITEM 
ITEMID 
Number(3) 
NAME 
Varchar2(15) 
1 Almirah 
2 Sofa 
3 Tea top 
4 Cane chair 
Primary Key: ITEMID 
Collections 
 In some online shopping web site, an item may be displayed by showing multiple 
images. To represent items, there should be a table holding multiple item 
entities. For each item entity, there can be one or more images. 
 The Item bean should have multiple references to ItemImage. These multiple 
references can be in the form of TreeSet, HashSet, ArrayList, HashMap, 
LinkedHashMap, TreeMap. 
© Onkar Deshpande
Collections 
 Set: A collection of unique entities. There are two 
implementations… 
 TreeSet: An ordered collection of unique entities. 
 HashSet: An un-ordered collection of unique entities. 
 Bag: An un-ordered collection of may be duplicate 
entities. There is no equivalent of it in Java. 
 List: An ordered collection of entities. Here order 
specifies the order of adding entities in collection. It 
allows duplicates. 
 Map: An un-ordered collection of Key-Value pairs. It has 
different implementations like… HashMap. 
LinkedHashMap, TreeMap etc. 
© Onkar Deshpande
ITEM 
ITEMID 
Number(3) 
NAME 
Varchar2(15) 
1 Almirah 
2 Sofa 
3 Tea top 
4 Cane chair 
Primary key: ITEMID 
ITEM_IMAGES 
ITEMID 
Number(3) 
FILENAME 
Varchar2(15) 
1 Almira image1 
1 Almira image2 
1 Almira image3 
3 Tea top image1 
3 Tea top image2 
4 Chair image3 
FK: ITEMID on ITEMID of ITEM 
Collections: Using Set 
public class Item { 
private int itemId; 
private String itemName; 
Set<String> images; 
…. 
} 
item.hbm.xml… 
<set name="images" lazy="true" table="ITEM_IMAGES" sort="natural"> 
<key column="ITEMID"/> 
<element type="string" column="FILENAME" not-null="true"/> 
</set> 
© Onkar Deshpande
ITEM 
ITEMID 
Number(3) 
NAME 
Varchar2(15) 
1 Almirah 
2 Sofa 
ITEM_IMAGES 
ITEM_IMAGES_SK 
(Num(3)) 
ITEMID 
Num(3) 
FILENAME 
Varchar2(15) 
1 1 Almira image1 
2 1 Almira image1 
3 1 Almira image1 
4 3 Tea top image1 
5 3 Tea top image1 
6 4 Chair image3 
FK: ITEMID on ITEMID of ITEM 
Collections: Using Bag 
public class Item { 
private int itemId; 
private String itemName; 
List<String> images; 
…. 
} 
item.hbm.xml… 
<idbag name="images" lazy="true" table="ITEM_IMAGES_SK"> 
<collection-id type="int" column="ITEM_IMAGES_SK"> 
<generator class="increment"/> 
</collection-id> 
<key column="ITEMID"/> 
<element type="string" column="FILENAME" not-null="true"/> 
</idbag> 
© Onkar Deshpande
ITEM 
ITEMID 
Number(3) 
NAME 
Varchar2(15) 
1 Almirah 
2 Sofa 
ITEM_IMAGES 
ITEMID 
Num(3) 
POSITION FILENAME 
Varchar2(15) 
1 0 Almira image1 
1 1 Almira image1 
1 2 Almira image1 
3 0 Tea top image1 
3 1 Tea top image1 
4 0 Chair image3 
FK: ITEMID on ITEMID of ITEM 
Collections: Using List 
public class Item { 
private int itemId; 
private String itemName; 
List<String> images; 
…. 
} 
item.hbm.xml… 
<list name="images" lazy="true" table="ITEM_IMAGES_POSI"> 
<key column="ITEMID"/> 
<index column="POSITION"/> 
<element type="string" column="FILENAME" not-null="true"/> 
</list> 
© Onkar Deshpande
ITEM 
ITEMID 
Number(3) 
NAME 
Varchar2(15) 
1 Almirah 
2 Sofa 
ITEM_IMAGES 
ITEMID 
Num(3) 
IMAGENAME 
(varchar2(15)) 
FILENAME 
Varchar2(15) 
1 FrontView Almira image1 
1 SideView Almira image1 
1 InnerView Almira image1 
3 FrontView Tea top image1 
3 SideView Tea top image1 
4 FrontView Chair image3 
public class Item { 
private int itemId; 
private String itemName; 
Map<String, String> images; 
FK: ITEMID on ITEMID of ITEM 
…. 
} 
item.hbm.xml… 
<map name="images" lazy="true" table="ITEM_IMAGES_MAP“ sort=“natural”> 
<key column="ITEMID"/> 
<index column="IMAGENAME" type="string"/> 
<element type="string" column="FILENAME" not-null="true"/> 
</map> 
Collections: Using Map 
© Onkar Deshpande
Module 6. The Association relations 
 Overview 
 The paradigm mismatch Association-OOPs and RDBMS 
 The Association-Multiplicity-Navigation 
 Understanding uni/bi-directional relationship 
 The One-One relationship 
 The One-many relationship 
 The Many-Many relationship 
 The Cascade clauses 
© Onkar Deshpande
The Association 
One to One Multiplicity 
Emp Profile 1 1 
One to Many Multiplicity 
Emp Department 0...* 1 
Many to Many Multiplicity 
Emp Project 0…* 0…* 
© Onkar Deshpande
The Association: One to One 
public class Emp { 
One to One Multiplicity 
Emp Profile 1 1 
private Integer empNo; 
private String eName; 
private String job; 
// One to one towards Profile 
private Profile profile; 
// Association scaffolding code 
public Profile getProfile() { 
return profile; 
} 
public void setProfile(Profile profile) { 
this.profile = profile; 
} 
} 
public class Profile { 
private int empId; 
private String skills; 
private String quali; 
// One to one towards emp 
private Emp emp; 
// Association scaffolding code 
public Emp getEmp() { 
return emp; 
} 
public void setEmp(Emp emp) { 
this.emp = emp; 
} 
} 
© Onkar Deshpande
The Association: One to One (Contd...) 
<class name="Emp" table="EMP"> 
<id name="empNo"> 
…… 
<property name="eName"> 
…… 
<one-to-one name="profile" // Name of setter method which executes association in Emp 
class="Profile" // Name of a class of object which is being associated with Emp. 
foreign-key="empId"// Name of a property in Profile which represents foreign key for Emp 
/> 
</class> 
<class name="Profile" table=“PROFILES"> 
<id name="empId"> 
….. 
<property name="skills"> 
….. 
<!-- For bi-directional navigation. --> 
<one-to-one name="emp" // Name of a setter method which establishes association in Profile 
class="Emp"// Name of a class of object which is being associated with Emp. 
property-ref="profile" // Name of a property in Emp which establishes Emp -> Profile relation. 
/> 
</class> 
© Onkar Deshpande
Cascade options 
Cascade Description 
none To ignore association 
save-update Persist transient object and all associated objects. Update 
association graph. 
delete Delete all associated persistent instances. 
all Cascade save-update, delete and evict and lock. 
all-delete-orphan Like cascade all + deletes all de-referenced objects also. 
delete-orphan Deletes all de-referenced objects also. 
Declaration in mapping file… 
<!-- cascade="save-update" cascade=“delete"--> 
<one-to-one name="profile“ class="Profile" 
foreign-key="empId" cascade=“save-update" 
/> 
© Onkar Deshpande
The Association: One to Many 
public class Emp { 
One to Many Multiplicity 
Emp Department 0…* 1 
private Integer empNo; 
private String eName; 
private String job; 
// One to one towards Profile 
private Profile profile; 
// Association scaffolding code 
public Profile getProfile() { 
return profile; 
} 
public void setProfile(Profile profile) { 
this.profile = profile; 
} 
} 
public class Dept { 
private int deptNo; 
private String deptNm; 
private Set<Emp> emps; // One to Many 
// Association scaffolding code 
public Set<Emp> getEmps(){ 
return emps; 
} 
public void setEmps(Set<Emp> emps){ 
this.emps = emps; 
} 
public void addEmps(Emp emp){ 
emp.setDepartment(this); 
emps.add(emp); 
} 
} 
© Onkar Deshpande
The Association: One to Many (Contd...) 
<hibernate-mapping package="com.hibernate.pack90_association.pack20_oneMany"> 
<class name="Emp" table="EMP"> 
<id name="empNo" column="EMPNO" length="4"> 
<generator class="assigned" /> 
</id> 
<property name="eName" column="ENAME" length="15" /> 
<property name="job" column="JOB" length="10" /> 
<many-to-one name="department" column="DEPTNO" class="Dept" 
not-null="true" /> <!-- lazy="false" --> 
</class> 
</hibernate-mapping> 
© Onkar Deshpande
The Association: Many to Many 
Many to Many Multiplicity 
Emp Project 0…* 0…* 
public class Emp { 
private Integer empNo; 
private String eName; 
private String job; 
// Many to many towards Project 
private Set<Project> projects; 
// Association scaffolding code 
public void setProjects(Set projects){ 
this.projects = projects; 
} 
public Projects getProjects(){ 
return projects; 
} 
} 
public class Project { 
private Integer projectId; 
private String projectTitle; 
// Many to Many towards Emp 
private Set<Emp> emps; 
// Association scaffolding code 
public Set<Emp> getEmployees() { 
return emps; 
} 
public void setEmployees(Set emps) { 
this.emps = emps; 
} 
} 
© Onkar Deshpande
The Association: Many to Many (Contd...) 
<class name="Project" table="PROJECT"> 
<id name="projectId" column="PROJECTID"> 
….. 
<property name="projectTitle" column="TITLE" /> 
<!-- Many to Many --> 
<set name="employees“ table=" EMP_PROJECT "> 
<key column="PROJECTID" /> 
<many-to-many class="Emp" column="EMPNO" /> 
</set> 
</class> 
<class name="Emp" table="EMP"> 
<id name="empNo" column="EMPNO" length="4"> 
……. 
<property name="eName" column="ENAME" length="15" /> 
<property name="job" column="JOB" length="10" /> 
<!-- Many to Many --> 
<set name="projects“ table=" EMP_PROJECT "> 
<key column="EMPNO" /> 
<many-to-many class="Project" column="PROJECTID" /> 
</set> 
</class> 
© Onkar Deshpande
Module 7. Hibernate Transaction support 
 Overview 
 Local and global transactions 
 Transactions in JDBC 
 Transactions in Hibernate 
 Transactions in non-managed and managed environments 
 Hibernate transaction API 
 JTA and Container Managed Transaction.(CMT) 
 Concurrency, locks and Isolation levels 
© Onkar Deshpande
Transaction 
Automatic steps 
Step 1---------------- 
Step 2---------------- 
Step 3---------------- 
Step 4---------------- 
Step 5---------------- 
Step 6---------------- 
Step 7---------------- 
If any one step 
is un-successful: 
Do nothing 
“Rollback” 
Only if all steps 
are successful: 
Persist state of 
all commands 
Commit 
Database 
© Onkar Deshpande
Local transaction 
 One service within a 
single program accessing 
single database. 
 Transactions confined to 
objects residing in one 
particular JVM. 
 The JDBC transaction on 
a connection is Local. 
Automatic steps 
Step 1---------------- 
Step 2---------------- 
Step 3---------------- 
Step 4---------------- 
Step 5---------------- 
Step 6---------------- 
Step 7---------------- 
Database 
© Onkar Deshpande
Global transaction 
 Transaction 
encapsulating object 
which are distributed on 
various JVMs. 
 Transactions on more 
than one resource 
managers where these 
managers are running on 
different servers. 
 A transaction with more 
than one databases. 
Automatic steps 
Step 1---------------- 
Step 2---------------- 
Step 3---------------- 
Step 4---------------- 
Step 5---------------- 
Database Database 
Server/JVM Server/JVM 
© Onkar Deshpande
Transaction in JDBC. 
To start a transaction bound to the connection. 
connection.setAutoCommit(false); 
To commit a transaction: 
connection.commit(); 
To roll back a transaction: 
connection.rollback(); 
Alternatives for ending transaction: 
1. setAutoCommit to true if set to 
false previously. 
2. Commit a transaction 
3. Rollback a transaction 
4. If timeout occurs, transaction 
rollsback. 
Local transactions can be turned off by adding following property to URL... 
disableLocalTxn=true 
© Onkar Deshpande
Transaction in Hibernate 
 Hibernate supports.. 
 JDBC transaction in non-managed environment 
 JTA transaction in managed environment. 
 Non-managed environment 
 An environment, data source is not provided as a ready resource. 
Ex. JDBC. 
 The managed environment 
 The environment manages connection, its pool and the data 
source. Servers (Web or appl) provide managed environments. 
 The Java Transaction API (JTA): 
 Manages distributed transaction 
 Allows declarative transaction 
 Supports Container Managed Transaction (CMT) 
© Onkar Deshpande
Hibernate Transaction API 
<interface> 
Transaction 
CORBATransaction JDBCTransaction JTATransaction 
© Onkar Deshpande
Hibernate Transaction API 
 session.beginTransaction(): 
 In non-managed environment: Starts a new JDBC transaction. 
 In managed environment: Starts new JTA transaction. 
 begin(): Starts a new transaction 
 commit(): Synchronizes session state with database. 
 rollback(): Forces underlying transaction to roll back. 
 isActive(): Is this transaction still active? 
 wasCommitted(): Check if this transaction was successfully 
committed. 
 wasRolledBack(): Was this transaction rolled back or set to 
roll back? 
 setTimeOut(int timeInSeconds): Sets the transaction time 
out. 
© Onkar Deshpande
Trasactional Attributes 
 Required 
 RequiresNew 
 Mandatory 
 Supports 
 NotSupported 
 Never 
© Onkar Deshpande
Transactional Attributes 
The Required (Default) attribute 
The declared method must be invoked within the scope of the transaction. 
Client (T1) T1 
Client T1 
Runs in propagated transaction T1 
Runs in New transaction T1 
The RequiredNew attribute 
The declared method must be invoked always in new transaction. 
Client (T1) T1 
Client T1 
Runs in propagated transaction T1 
Runs in New transaction T1 
© Onkar Deshpande
Transactional Attributes 
The Supports attribute 
The declared method is included in transaction scope if invoked within a 
transaction. 
Client (T1) T1 
Client Method 
Runs in propagated transaction T1 
Runs without transaction 
The NotSupported attribute 
The declared method when invoked within transaction scope, suspends 
transaction until method completes 
Client (T1) Method Runs without transaction 
© Onkar Deshpande
Transactional Attributes 
The Mandatory attribute 
The declared method is included in transaction scope if invoked within a transaction 
Client (T1) T1 
Client Method 
Runs in propagated transaction T1 
Throws exception when run 
without transaction. 
The Never attribute 
The declared method must never be invoked in any 
Client (T1) T1 
Client Method 
Throws exception when run 
within transaction 
Runs without transaction 
© Onkar Deshpande
Isolation Issues 
 Lost update 
 Dirty read 
 Unrepeatable read 
 Second lost update 
 Phantom read 
© Onkar Deshpande
Isolation Levels 
Isolation levels and their values 
Read Uncommitted 1 
Read Committed 2 
Repeatable Read 4 
Serializable 8 
 Every JDBC connection uses database default value of 
isolation. 
 Explicit setting of isolation level can be done by 
introducing following entry into cfg file. 
 hibernate.connection.isolation=2 
© Onkar Deshpande
Locking 
 A mechanism that prevents concurrent access to the 
particular item of data. 
 A transaction has to acquire a lock for reading or 
modifying the item. 
 Types of locks: 
 Pessimistic 
 Optimistic 
© Onkar Deshpande
Pessimistic Locks 
 It is acquired when item of data is read and held until 
transaction is completed. 
 Some databases allow locking with Select – For Update 
clause. 
 Hibernate’s different lock modes... 
 LockMode.NONE 
 LockMode.READ 
 LockMode.UPGRADE 
 LockMode.UPGRADE_NOWAIT 
 Category cat = (Category) session.get(Category.class, catId, 
LockMode.UPGRADE); 
 It loads category with Select…For Update and locks the 
retrieved row until transaction ends. 
© Onkar Deshpande
Pessimistic Locks 
 Except NONE all lock modes makes hibernate to go to 
DB. 
 The load() and get() by default uses LockMode.NONE. 
 The LockMode.READ needs on detached object with 
lock() to check version of corresponding row. 
 The LockMode.UPGRADE locks a row at DB side 
thereby hampering scalability. 
 The strict locking at application side hampers 
performance of other applications. 
© Onkar Deshpande
Optimistic Locks 
An additional column in table for Version or TimeStamp managed automatically by 
hibernate every time object is modified 
public class Item { 
------- 
int version; 
public int getVersion(){ 
return version; 
} 
public void setVersion(int v){ 
this.version = v; 
} 
OR 
Date timeStamp; 
public void setLastUpdateDateTime(Date dt){ 
this.timeStamp = dt; 
} 
public Date getLast… 
} 
<class name=“item” table=“ITEM”> 
<id>…</id> 
<version name=“version” column=“VERSION” /> 
</class> 
OR 
<class name=“item” table=“ITEM”> 
<id>…</id> 
<timestamp name=“lastUpdateDateTime” 
column=“UPDATE_DATE” /> 
</class> 
© Onkar Deshpande
Module 8. Queries in Hibernate 
 Overview 
 Object retrieving 
 Why HQL? 
 Working with HQL 
 Working with Native queries 
 Working with Criteria queries 
© Onkar Deshpande
Retrieving Objects 
 Navigating object graph. 
 aUser.getAddress().getCity() 
 Retrieving by identifier. 
 User user = (User) session.get(User.class, userId); 
 Using Hibernate Query Language (HQL) 
 String qry = “from Emp e order by e.job asc, e.sal desc”; 
 List<Emp> empList = session.createQuery(qry ); 
 Using Criteria API 
 Criterion restriction = Expression.eq("empNo", 7499); 
 Emp emp = (Emp) session.createCriteria(Emp.class).add( restriction ).uniqueResult(); 
 Using Query By Example (QBE) 
 QueryOnEmp queryByExample = new QueryOnEmp(); 
 queryByExample.seteName("J%"); 
 queryByExample.setJob("MANAGER"); 
 String queryString_HQL = "from Emp emp where emp.eName like :ename and emp.job like :job"; 
 List<Emp> emps = session.createQuery(queryString_HQL).setProperties(queryByExample).list(); 
 Using Native Query Language (NQL) 
 String qry = “select {i.*} from EMP {i} order by JOB asc, SAL desc”; 
 List<Emp> empList = session.createSQLQuery(qry ); 
© Onkar Deshpande
Hibernate Query Language 
 Query to get all employees from table. 
 Query qryForAllEmployees = session.createQuery("from Emp"); 
 List<Emp> empList = qryForAllEmployees.list(); 
 Query to get objects in pages in given order. 
 String qry = “from Emp e order by e.job asc, e.sal desc”; 
 Query qryForAllEmployees = session.createQuery(qry); 
 qryForAllEmployees.setFirstResult(0); 
 qryForAllEmployees.setMaxResults(5); 
 List<Emp> empList = qryForAllEmployees.list(); 
 Query for unique result. Using positional parameters, Binding 
parameters 
 Emp emp = (Emp) session.createQuery("from Emp e where e.empNo = 
?").setInteger(0, 7499).uniqueResult(); 
 Query for list with named parameters 
 List<Emp> empList = session.createQuery("from Emp e where e.eName like 
:name").setString( “A%”, eName,).list(); 
© Onkar Deshpande
Hibernate Query Language (Contd...) 
 Query for property value ‘null’ 
 List<Emp> emps = session.createQuery("from Emp as e where e.mgr is null").list(); 
 Query with between clause 
 Query qryForAllEmployees = session.createQuery("from Emp where empNo 
between :vl1 and vl2").setInteger(“vl1”, 7500).setInteger(“vl2”, 8000); 
 Query with ‘in’ clause… 
 from Emp where empNo in (7369, 7499) 
 Query with logical operators 
 from Emp where eName like :name And job like :job 
 from Emp where eName like :name Or job like :job. 
 Writing group queries. 
 select count(*) from Emp 
 select sum(sal) from Emp 
© Onkar Deshpande
Criteria Queries 
 Criteria for all employees 
 Criteria qryForAllEmployees = session.createCriteria(Emp.class); 
 List<Emp> empList = qryForAllEmployees.list(); 
 Criteria to get objects in pages in given order. 
 List<Emp> empList = session.createCriteria(Emp.class) 
 .addOrder( Order.asc("job") ) 
 .addOrder( Order.desc("sal")) 
 .setFirstResult(0) 
 .setMaxResults(5) 
 .list();. 
 Criteria for unique result. Binding parameters 
 Criterion restriction = Expression.eq("empNo", 7499); 
 Emp emp = (Emp) session.createCriteria(Emp.class).add( restriction ).uniqueResult(); 
 Criteria for list with named parameters 
 List<Emp> empList = session.createCriteria(Emp.class) 
 .add(Expression.ilike("J%“, "eName")).list(); 
© Onkar Deshpande
Criteria Queries (Contd...) 
 Criteria with restriction on value ‘null’ 
 List<Emp> emps = session.createCriteria(Emp.class).add(Expression.isNull("mgr")).list(); 
 Criterion for between and in clauses. 
 Criterion restriction = Expression.between("empNo", 7800, 7900); 
 Criterion restriction = Expression.in("empNo", new Object[]{7369, 7499}); 
 Criteria query with logical operators- And 
 Criterion restriction1 = Expression.like("eName", "J%"); 
 Criterion restriction2 = Expression.like("job", "MANAGER"); 
 List<Emp> empList = session.createCriteria(Emp.class) 
 .add(restriction1) 
 .add(restriction2) 
 .list(); 
 Criteria with restriction with complex boolean expression. 
 Criterion restriction1 = Expression.like("eName", "J%"); 
 Criterion restriction2 = Expression.like("job", "MANAGER"); 
 Criterion restriction3 = Expression.or(restriction1, restriction2); 
 Criterion restriction4 = Expression.gt("sal", 2500f); 
 Criterion restriction5 = Expression.and(restriction3, restriction4); 
 List<Emp> empList = session.createCriteria(Emp.class) 
 .add(restriction5) 
 .list(); 
© Onkar Deshpande
Native Query Language 
 Query to get all employees from table. 
 SQLQuery qryForAllEmployees = session.createSQLQuery("select {i.*} from EMP 
{i}"); 
 List<Emp> empList = qryForAllEmployees.addEntity("i", Emp.class).list() 
 Query to get objects in pages in given order. 
 String qry = “select {i.*} from EMP {i} order by JOB asc, SAL desc" 
 List<Emp> empList= session.createSQLQuery(qry ) 
 .addEntity("i", Emp.class) 
 .setFirstResult(0) 
 .setMaxResults(5).list(); 
 Query for unique result. Using positional parameters, Binding parameters 
 String qry = “select {i.*} from EMP {i} where EMPNO like ?" 
 Emp emp = (Emp) session.createSQLQuery(qry ) 
 .addEntity("i", Emp.class) 
 .setInteger(0, 7499).uniqueResult(); 
© Onkar Deshpande
Native Query Language (Contd...) 
 Query for list with named parameters 
 String qry = “select {i.*} from EMP {i} where EMPNO like :empNo”; 
 Emp emp = (Emp) session.createSQLQuery(qry) 
 .addEntity("i", Emp.class) 
 .setInteger("empNo", 7499).uniqueResult(); 
 Query for property value ‘null’ 
 select {i.*} from EMP {i} where MGR is null 
 Query with between and in clause 
 select {i.*} from EMP {i} where EMPNO between :val1 and :val2 
 select {i.*} from EMP {i} where EMPNO in (:val1, :val2) 
© Onkar Deshpande
Module 9. Advanced queries 
 Overview 
 Query by example 
 Named queries 
 Report queries 
 Fetching strategies and joins 
© Onkar Deshpande
Query by example 
public class QueryOnEmp { 
private String ename; 
private String job; 
public String geteName() { return ename; } 
public void seteName(String ename) { this.ename = ename; } 
public String getJob() { return job; } 
public void setJob(String job) { this.job = job; } 
} 
QueryOnEmp queryByExample = new QueryOnEmp(); 
queryByExample.seteName("J%"); 
queryByExample.setJob("MANAGER"); 
© Onkar Deshpande
Report Queries 
 Projection with Object array 
String qry = "select emp.empNo, emp.eName, emp.sal from Emp emp"; 
Iterator i = session.createQuery(qry) list().iterator(); 
while ( i.hasNext() ) { 
Object[] row = (Object[]) i.next(); 
Integer empNo = (Integer) row[0]; 
String eName = (String) row[1]; 
Float sal = (Float) row[2]; 
System.out.println("Number:"+empNo+"tName:"+eName+"tSal:"+sal); 
} 
 Projection with dynamic instantiation. 
String qry = "select new EmpRow(e.empNo, e.eName, e.sal) from Emp e"; 
Iterator i = session.createQuery(qry).list().iterator(); 
while ( i.hasNext() ) { 
EmpRow emp = (EmpRow) i.next(); 
System.out.println(emp); 
} 
© Onkar Deshpande
Named Queries 
1. A technique to externalize query. 
2. All queries to be accumulated in separate XML file. 
3. The code is not cluttered up with queries. 
4. Code identifies queries using their unique names. 
<!-- Named Queries --> 
<query name="findEmpsByName-HQL"> 
<![CDATA[from Emp emp where emp.eName like :name]]> 
</query> 
<sql-query name="findEmpsByName-SQL"> 
<![CDATA[select {i.*} from EMP {i} where ENAME like :name]]> 
<return alias="i" class="Emp"/> 
</sql-query> 
List<Emp> empList = session.getNamedQuery("findEmpsByName-SQL") 
.setString("name", "J%").list(); 
List<Emp> empList = session.getNamedQuery("findEmpsByName-HQL") 
.setString("name", "J%").list(); 
© Onkar Deshpande
Joins 
 Inner Joins: All items that have bids 
 Left outer Joins: All items with their bids and also items 
without bids. 
 Right Joins: All items with their bids and all bids which are 
not on any item (Not applicable here). 
 Theta style joins: 
 Implicit Joins Uses multiple property paths for expressing implicit 
associations or querying components. 
Item 
Bid bids 
//Setter 
//getter 
Bid 
Item item 
//Setter 
//getter 
1 0..* 
© Onkar Deshpande
Joins 
Inner Joins 
Select bid from Bid bid inner join bid.item 
OR 
Select bid from Bid bid join bid.item 
select i.name, b.bid_id, from Bids b join Items i on i.item_id = b.item_id 
Outer Joins: 
Select bid from Bid bid left join fetch bid.item 
Select bid from Bid bid left outer join bid.item 
Select bid from Bid bid right outer join bid.item; 
select i.name, b.bid_id, from Bids b left join Items i on i.item_id = b.item_id 
select i.name, b.bid_id, from Bids b right join Items i on i.item_id = b.item_id 
© Onkar Deshpande
Joins 
Implicit Joins 
Select bid from Bid bid where bid.item.itemId!=1 
Select bid from Bid bid where bid.item.itemId is null 
select i.name, b.bid_id from Bids b join Items i on i.item_id = b.item_id where 
i.item_id is null; 
Implicit Joins 
Select bid from Bid bid where bid.item.itemId!=1 
Select bid from Bid bid where bid.item.itemId is null 
Theta style Joins: 
Select i.name, b.bidId from Item i, Bid b where bid.bidId > 5 
from Item, Bid // Gives Cartesian product 
Criteria doesn’t provide Theta style joins and Cartesian product. 
Hibernate does not support outer join on two tables which are not associated. 
© Onkar Deshpande
Fetching 
Types of fetching 
• Immediate 
• Lazy 
• Eager 
• Batch 
• Its normal practice to define lazy fetching in mapping files. 
• In the code, ‘fetch’ keyword overrides lazy fetching. Thus 
code decides the fetching strategy. 
select i.name, b.bid_id, from Bids b join fetch Items i on i.item_id = b.item_id 
select i.name, b.bid_id, from Bids b left join fetch Items i on i.item_id = b.item_id 
select i.name, b.bid_id, from Bids b right join fetch Items i on i.item_id = b.item_id 
© Onkar Deshpande
Module 10. More on Hibernate 
 Overview 
 Automating naming conventions. 
 Dynamic alterations to context 
 Connection pooling 
 Hibernate in web application 
 Building database structure through Mapping files. 
 Caching support in Hibernate. 
 Using Log4J with Simple Logger Facad. 
 Hibernate in Spring 
© Onkar Deshpande
Naming Convensions 
The emb.hbm.xml 
<class name="Emp"> 
<id name="empNo" > 
<generator class="assigned"/> 
</id> 
<property name="eName" /> 
<property name="sal" l/> 
……. 
</class> 
Building Session 
SessionFactory sessions = new Configuration() 
.configure(relativePathToConfig) 
.setNamingStrategy( new PRConvensions() ) 
.buildSessionFactory(); 
Code referring Emp 
Query queryForEmps = session.createQuery("from Emp"); 
List<Emp> empList = queryForEmps.list(); 
for(Emp emp : empList){ 
System.out.println(emp); 
} 
© Onkar Deshpande
Naming Convensions (Contd...) 
public class PRConvensions implements NamingStrategy { 
private String className; 
public String tableName(String tableName) { 
return "PR_" + tableName; 
} 
public String classToTableName(String className) { 
this.className = StringHelper.unqualify(className).toUpperCase(); 
return tableName( this.className ); 
} 
public String propertyToColumnName(String propertyName) { 
return className+"_"+propertyName.toUpperCase(); 
} 
public String propertyToTableName(String className, String propertyName) { 
return classToTableName(className) + '_' 
+propertyToColumnName(propertyName); 
} 
public String columnName(String columnName) { 
return "PR_"+columnName; 
} 
© Onkar Deshpande
Dynamic Context manipulation 
Configuration cfg = new Configuration().configure(relativePathToConfig); 
// Get the existing mapping for User from Configuration 
PersistentClass userMapping = cfg.getClassMapping("pack950_moreHiber.pack20_dynaMetadata.Emp"); 
// Define a new column for the EMP table 
Column column = new Column(); 
column.setSqlType("varchar2"); 
column.setName("EMP_MOTTO"); 
column.setNullable(true); 
column.setUnique(false); 
Table table = userMapping.getTable(); 
able.addColumn(column); 
// Wrap the column in a Value 
SimpleValue value = new SimpleValue(null, null); 
value.setTable( userMapping.getTable() ); 
value.addColumn(column); 
value.setTypeName("string"); 
// Define a new property of the User class 
Property prop = new Property(); 
prop.setValue(value); 
prop.setName("motto"); 
prop.setNodeName("motto"); 
userMapping.addProperty(prop); 
© Onkar Deshpande
Connection Pooling 
Why Connection pools? 
• Acquiring new connection is expensive 
• Maintaining many idle connections is expensive 
• Creating prepared statements for some drivers is expensive 
What is connection pool? 
• Holds live connections. On demand supply them. 
• Can automatically change pool size as per utilization of connections. 
• Provides utmost scalability of connections. 
• The DriverManager manages connections. 
In managed environment 
Connection pools and Driver Manager are created by environment and provided as a service to 
all applications running under environment. 
In non-managed environment 
The third party tool can be used to avail feature. Hibernate has inbuilt support for C3P0. 
Hibernate Configuration… 
<property name="hibernate.c3p0.min_size">5</property> 
<property name="hibernate.c3p0.max_size">20</property> 
<property name="hibernate.c3p0.timeout">300</property> 
<property name="hibernate.c3p0.max_statements">50</property> 
<property name="hibernate.c3p0.idle_test_period">3000</property> 
© Onkar Deshpande
Hibernate in web application 
The SessionFactory: It is thread safe and cluster safe. Heavy weight. 
Should be created once in an application. 
The Session: Not thread safe. Execute its instance in single thread. Light 
weight, should be created and destroyed in a method or for a request. 
The PersistentUtil 
private static final SessionFactory sessionFactory; // To create once 
// Session and transaction for each request. 
private static final ThreadLocal<Session> threadSession 
= new ThreadLocal<Session>(); 
private static final ThreadLocal<Transaction> threadTransaction 
= new ThreadLocal<Transaction>(); 
© Onkar Deshpande
Hibernate in web application 
Getting a session: 
Session session = sessionFactory.openSession(); 
threadSession.set(session); 
Getting Transaction: 
Transaction transaction = session.beginTransaction(); 
threadTransaction.set(transaction); 
Committing or Rolling back Transaction 
Transaction tx = threadTransaction.get(); 
if ( tx != null && !tx.wasCommitted() && !tx.wasRolledBack() ) { 
tx.commit(); / tx.rollBack(); 
threadTransaction.set(null); 
} 
Closing Session 
Session session = (Session) threadSession.get(); 
threadSession.set(null); 
if (session != null && session.isOpen()) 
session.close(); 
© Onkar Deshpande
Table structure from mapping files. 
 Its an approach of development where entities are 
identified as classes and from mapping file, Hibernate 
creates a table structure with all necessary associations 
and inheritance. 
 Hibernate does not support creating classes from table 
structure (iBatis supports). 
 The cfg file. 
 <property name="hibernate.hbm2ddl.auto">update</property> 
 If hibernate finds that table is existing but with 
mismatch in fields with table, columns are altered in 
table. 
© Onkar Deshpande
Caching support in Hibernate. 
 There are two levels of caching… 
 Transactional Cache/First level cache provided by Hibernate 
Session. 
 Global Cache/Second level cache provided by Cache provider. 
 All transient objects are entitled for caching. 
 By default hibernate queries always ignore cache. 
 If second level cache is enabled, FLC contents are written to 
SLC. 
 The query is cached only if it is explicitly cached. 
 To explicitly cache query, Query interface has method 
setCacheable(); 
 The SessionFactory has special API to view IInd level cache 
statistic. 
© Onkar Deshpande
Caching support in Hibernate. 
 Enabling IInd level cache. 
 hibernate.cache.use_second_level_cache = true 
 hibernate.cache.use_query_cache = true 
 hibernate.cache.provider_class = et.sf.hibernate.cache.QueryCache 
 Third party IInd level cache. 
 EhCache, TerraCota, TreeCache, SwarmCache, oscache 
© Onkar Deshpande

More Related Content

What's hot (19)

PPTX
Hibernate ppt
Aneega
 
PPT
Introduction to Hibernate
Krishnakanth Goud
 
PPTX
Spring (1)
Aneega
 
ODP
Hibernate Developer Reference
Muthuselvam RS
 
PPTX
Hibernate in Action
Akshay Ballarpure
 
PPT
Hibernate presentation
Manav Prasad
 
PDF
Hibernate 3
Rajiv Gupta
 
PDF
Introduction to JPA and Hibernate including examples
ecosio GmbH
 
PDF
JPA and Hibernate
elliando dias
 
PDF
Hibernate An Introduction
Nguyen Cao
 
DOC
Hibernate tutorial for beginners
Rahul Jain
 
PPT
Hibernate
Ajay K
 
PPS
Java Hibernate Programming with Architecture Diagram and Example
kamal kotecha
 
PPT
Java Persistence API (JPA) Step By Step
Guo Albert
 
PPT
jpa-hibernate-presentation
John Slick
 
PDF
Hibernate Presentation
guest11106b
 
PDF
Data access
Joshua Yoon
 
PPT
Hibernate architecture
Anurag
 
Hibernate ppt
Aneega
 
Introduction to Hibernate
Krishnakanth Goud
 
Spring (1)
Aneega
 
Hibernate Developer Reference
Muthuselvam RS
 
Hibernate in Action
Akshay Ballarpure
 
Hibernate presentation
Manav Prasad
 
Hibernate 3
Rajiv Gupta
 
Introduction to JPA and Hibernate including examples
ecosio GmbH
 
JPA and Hibernate
elliando dias
 
Hibernate An Introduction
Nguyen Cao
 
Hibernate tutorial for beginners
Rahul Jain
 
Hibernate
Ajay K
 
Java Hibernate Programming with Architecture Diagram and Example
kamal kotecha
 
Java Persistence API (JPA) Step By Step
Guo Albert
 
jpa-hibernate-presentation
John Slick
 
Hibernate Presentation
guest11106b
 
Data access
Joshua Yoon
 
Hibernate architecture
Anurag
 

Similar to Hibernate in Nutshell (20)

PPT
Hibernate
Shaharyar khan
 
PPT
Basic Hibernate Final
Rafael Coutinho
 
PPTX
Hibernate example1
myrajendra
 
PPT
Hibernate for Beginners
Ramesh Kumar
 
PPT
5-Hibernate.ppt
ShivaPriya60
 
PDF
inf5750---lecture-2.-c---hibernate-intro.pdf
bhqckkgwglxjcuctdf
 
PPTX
Module-3 for career and JFSD ppt for study.pptx
ViratKohli78
 
ODP
Hibernate 18052012
Manisha Balwadkar
 
PDF
Hibernate notesforprofessionals
Right
 
PPTX
Hibernate
Mallikarjuna G D
 
PPT
Hibernate jj
Joe Jacob
 
PPT
Hibernate introduction
Sagar Verma
 
DOCX
4.3 Hibernate example.docx
yasothamohankumar
 
PPTX
Hibernate in XPages
Toby Samples
 
PPTX
Session 39 - Hibernate - Part 1
PawanMM
 
PPT
Hibernate
Preetha Ganapathi
 
PDF
Hibernate interview questions
venkata52
 
PPT
Hibernate Session 1
b_kathir
 
PPT
Hibernate
Murali Pachiyappan
 
Hibernate
Shaharyar khan
 
Basic Hibernate Final
Rafael Coutinho
 
Hibernate example1
myrajendra
 
Hibernate for Beginners
Ramesh Kumar
 
5-Hibernate.ppt
ShivaPriya60
 
inf5750---lecture-2.-c---hibernate-intro.pdf
bhqckkgwglxjcuctdf
 
Module-3 for career and JFSD ppt for study.pptx
ViratKohli78
 
Hibernate 18052012
Manisha Balwadkar
 
Hibernate notesforprofessionals
Right
 
Hibernate
Mallikarjuna G D
 
Hibernate jj
Joe Jacob
 
Hibernate introduction
Sagar Verma
 
4.3 Hibernate example.docx
yasothamohankumar
 
Hibernate in XPages
Toby Samples
 
Session 39 - Hibernate - Part 1
PawanMM
 
Hibernate interview questions
venkata52
 
Hibernate Session 1
b_kathir
 
Ad

Recently uploaded (20)

PPTX
Java Native Memory Leaks: The Hidden Villain Behind JVM Performance Issues
Tier1 app
 
PDF
Alarm in Android-Scheduling Timed Tasks Using AlarmManager in Android.pdf
Nabin Dhakal
 
DOCX
Import Data Form Excel to Tally Services
Tally xperts
 
PDF
Beyond Binaries: Understanding Diversity and Allyship in a Global Workplace -...
Imma Valls Bernaus
 
PDF
Thread In Android-Mastering Concurrency for Responsive Apps.pdf
Nabin Dhakal
 
PPTX
Migrating Millions of Users with Debezium, Apache Kafka, and an Acyclic Synch...
MD Sayem Ahmed
 
PPTX
Feb 2021 Cohesity first pitch presentation.pptx
enginsayin1
 
PDF
Automate Cybersecurity Tasks with Python
VICTOR MAESTRE RAMIREZ
 
PDF
Efficient, Automated Claims Processing Software for Insurers
Insurance Tech Services
 
PDF
vMix Pro 28.0.0.42 Download vMix Registration key Bundle
kulindacore
 
PPTX
How Apagen Empowered an EPC Company with Engineering ERP Software
SatishKumar2651
 
PDF
iTop VPN With Crack Lifetime Activation Key-CODE
utfefguu
 
PDF
Salesforce CRM Services.VALiNTRY360
VALiNTRY360
 
PPTX
Fundamentals_of_Microservices_Architecture.pptx
MuhammadUzair504018
 
PPTX
MailsDaddy Outlook OST to PST converter.pptx
abhishekdutt366
 
PDF
Powering GIS with FME and VertiGIS - Peak of Data & AI 2025
Safe Software
 
PPTX
Engineering the Java Web Application (MVC)
abhishekoza1981
 
PDF
Linux Certificate of Completion - LabEx Certificate
VICTOR MAESTRE RAMIREZ
 
PPTX
Agentic Automation Journey Session 1/5: Context Grounding and Autopilot for E...
klpathrudu
 
PPTX
Platform for Enterprise Solution - Java EE5
abhishekoza1981
 
Java Native Memory Leaks: The Hidden Villain Behind JVM Performance Issues
Tier1 app
 
Alarm in Android-Scheduling Timed Tasks Using AlarmManager in Android.pdf
Nabin Dhakal
 
Import Data Form Excel to Tally Services
Tally xperts
 
Beyond Binaries: Understanding Diversity and Allyship in a Global Workplace -...
Imma Valls Bernaus
 
Thread In Android-Mastering Concurrency for Responsive Apps.pdf
Nabin Dhakal
 
Migrating Millions of Users with Debezium, Apache Kafka, and an Acyclic Synch...
MD Sayem Ahmed
 
Feb 2021 Cohesity first pitch presentation.pptx
enginsayin1
 
Automate Cybersecurity Tasks with Python
VICTOR MAESTRE RAMIREZ
 
Efficient, Automated Claims Processing Software for Insurers
Insurance Tech Services
 
vMix Pro 28.0.0.42 Download vMix Registration key Bundle
kulindacore
 
How Apagen Empowered an EPC Company with Engineering ERP Software
SatishKumar2651
 
iTop VPN With Crack Lifetime Activation Key-CODE
utfefguu
 
Salesforce CRM Services.VALiNTRY360
VALiNTRY360
 
Fundamentals_of_Microservices_Architecture.pptx
MuhammadUzair504018
 
MailsDaddy Outlook OST to PST converter.pptx
abhishekdutt366
 
Powering GIS with FME and VertiGIS - Peak of Data & AI 2025
Safe Software
 
Engineering the Java Web Application (MVC)
abhishekoza1981
 
Linux Certificate of Completion - LabEx Certificate
VICTOR MAESTRE RAMIREZ
 
Agentic Automation Journey Session 1/5: Context Grounding and Autopilot for E...
klpathrudu
 
Platform for Enterprise Solution - Java EE5
abhishekoza1981
 
Ad

Hibernate in Nutshell

  • 1. Hibernate 3.6 © Onkar Deshpande
  • 2. Table of Contents Module Title Page 1 Introduction to Hibernate 3 2 Getting started 13 3 Hibernate API for CRUD 21 4 Some mapping clauses 29 5 More mapping concepts 40 6 The Association relations 55 7 Hibernate Transaction Support 64 8 Queries in Hibernate 82 9 Advanced queries 92 10 More on hibernate 102 © Onkar Deshpande
  • 3. Module 1. Introduction to Hibernate  Overview  Database layer tools-Wrappers and ORM  What is hibernate?  OOPs and RDBMS paradigm mismatch  The ORM solutions  Hibernate Vs. JPA  Hibernate architecture © Onkar Deshpande
  • 4. Database layer tools OOPS Business Layer Service Layer Presentation Layer JDBC Layer JDBC Wrapper Spring JDBC JPA Hibernate iBatis Database © Onkar Deshpande
  • 5. 5 Hibernate Clients Desktop application Console/Swing Spring application EJB Container Web application Struts/WebWork/TabeStray Hibernate Database © Onkar Deshpande
  • 6. What is Hibernate?  What is hibernate?  A powerful ORM tool to design data base access layer.  Fills gaps of mismatches between OOPs and RDBMS paradigm. Also maintains adequate ultra performance of database access.  An automated, configurable persistence of java objects with tables in data base.  May not be a good solution for data-centric application which uses only stored procedures to implement business logic in the database. © Onkar Deshpande
  • 7. Hibernate versions  Hibernate 3.2  Most commonly used production version.  Full support for JPA 1.0.  Hibernate 3.5  Full support for JPA 2.0.  Hibernate 3.6  Full support of JEE 5.  Hibernate 4.1  Full Support to JEE 6  Hibernate 4.3  Full Support to JEE 7 © Onkar Deshpande
  • 8. Paradigm mismatch  Problem of Granularity.  Problem of subtypes.  Problem of identity.  Problems relating to association.  Problem of object graph navigation. © Onkar Deshpande
  • 9. The ORM solutions  Wrapper for basic CRUD operations.  Language or API for specifying queries that refers to Objects and their properties.  Facility for specifying mapping metadata.  Techniques to match the mismatches between OOPs and Databases.  Dirty checking, lazy fetching, and other optimization functions. © Onkar Deshpande
  • 10. Hibernate Vs. JPA  JPA is set of specifications of which implementation is provided in Toplink, hibernate 3.0 etc.  JPA is a standard while hibernate is not.  JPA ‘s some of the implementations have been blamed as slow.  EntityManager and EntityManagerFactory are thin wrappers around Session and SessionFactory etc. © Onkar Deshpande
  • 11. Hibernate Architecture Overview of Hibernate in layered architecture Business Layer Persistent Layer Persistence Classes Session Query User Types Interceptors Session Factory Configuration Transaction © Onkar Deshpande
  • 12. Hibernate Architecture Overview of Hibernate in layered architecture Business Layer Persistent Layer Persistence Classes Session Query User Types Interceptors Session Factory Configuration Transaction © Onkar Deshpande
  • 13. Module 2. Getting started  Overview  Hibernate Configuration- XML and properties  Mapping tables with beans  Hibernate SessionFactory and Session  Mapping using annotations  Object states. © Onkar Deshpande
  • 14. Configuration using XML <hibernate-configuration> <session-factory> <property name="hibernate.connection.driver_class">oracle.jdbc.OracleDriver</property> <property name="hibernate.connection.url">jdbc:oracle:thin:@localhost:1521:ORCL</property> <property name="hibernate.connection.username">scott</property> <property name="hibernate.connection.password">tiger</property> <property name="hibernate.connection.pool_size">10</property> <property name="show_sql">true</property> <property name="hibernate.use_sql_comments">true</property> <property name="dialect">org.hibernate.dialect.Oracle9Dialect</property> <mapping resource="comhibernatepack10_beginempBean.hbm.xml"/> </session-factory> </hibernate-configuration> © Onkar Deshpande
  • 15. Mapping tables with beans Mapping metadata… <hibernate-mapping> <class name="com.hibernate.pack10_begin.EmpBean" table="EMP"> <id name="empNo" type="int" column="EMPNO" > <generator class="native"/> </id> <property name="ename"> <column name="ENAME" /> </property> <property name="sal"> <column name="EMPSAL"/> </property> </class> </hibernate-mapping> public class EmpBean { private int empNo; private String empNm; private Float empSal; public void setEmpNo(int empNo) { this.empNo = empNo; } public void setEname(String empNm) { this.empNm = empNm; } public void setSal(Float empSal) { this.empSal = empSal; }} © Onkar Deshpande
  • 16. SessionFactory and Session  Booting steps...  Create configuration object. Configuration config = new Configuration(); config.configure(“pack10_beginhibernate_begin.cfg.xml”);  Build session factory. SessionFactory sessions = config.buildSessionFactory();  Open session Session session = sessions.openSession();  Start transaction Transaction transaction = session.beginTransaction();  Handle session session.save(), session.update() etc.  Conclude transaction transaction.commit(), transaction.rollback()  Close session.  session.close() © Onkar Deshpande
  • 17. Mapping using annotations. @ Entity @ Table (name="emp") public class EmpBean { private int empNo; private String empNm; private Float empSal; @ Id @ Column(name="EMPNO") public int getEmpNo() { return empNo; } } Configuration in xml… <mapping class=“hiber10annot.EmpBean"/> © Onkar Deshpande
  • 18. Object States  Transient  Persistent  Detached © Onkar Deshpande
  • 19. Transient Object states JVM Database Persistence Heap Stack Context Scott 21 1000 2-01-12 Reference Session © Onkar Deshpande
  • 20. Persistent Object states JVM Database Persistence Heap Stack Context Scott 21 1000 2-1-12 Reference Session Name Age Salary DOJ Scott 21 1000 2-1-12 Reference © Onkar Deshpande
  • 21. Detached Object states JVM Database Persistence Heap Stack Context Scott 21 1000 2-1-12 Reference Session Name Age Salary DOJ Scott 21 1000 2-1-12 Reference © Onkar Deshpande
  • 22. Module 3. Hibernate API for CRUD  Overview  The CRUD operations using beans  The CRUD operations using XML  The CRUD operations using Maps © Onkar Deshpande
  • 23. Object Retrieving  Navigating object graph  Using get()/load() method.  Using HQL. © Onkar Deshpande
  • 24. Object Retrieving  Using Criteria queries.  Using Query by example.  Using native queries. © Onkar Deshpande
  • 25. Insert a record Inserts a persistent object into table at the time of commit(). Throws exception on violation of any constraint at DB. save() persist() Hibernate specific Standard as per JSR 220. Returns auto generated primary key Does not return any value. Update a record Dirty check is default feature for persistent object. But for transient object, update or merge does update at DB side and makes object as persistent. update() merge() Hibernate specific Standard as per JSR 220. Update the record in DB. Makes an trans.or detached object persistent. Copies content of transient object into persistent object. If there is no persistent object in session, it is loaded. CRUD operations © Onkar Deshpande
  • 26. Delete a record Delete a given record from table provided it exists. Otherwise thros exception. Converts persistent object into transient state. delete() Retrieve a record Returns persistent object of the given class and given record it. get() load() Standard as per JSR 220. Hibernate specific Returns initialized instance only if record is existing. Returns proxy assuming instance is existing. Returns null if record is missing. Throws exception later if record is missing. Use to get instance or to check existence of a record. Old version. Use to get instance if record surely exists. CRUD operations © Onkar Deshpande
  • 27. Data formats for CRUD operations  Using plain old java objects: Exchanging DB data with OOPs paradigm.  Using Maps: Facilitate dynamic change in structure of data.  Using XML: For exchanging DB data with XML data source. © Onkar Deshpande
  • 28. Map format for CRUD operations Mapping…. <class entity-name="message" table="MESSAGES" > <id name="id" column="MESSAGE_ID" type="long"> <generator class="increment"/> </id> <property name="text" column="MESSAGE_TEXT" type="string"/> <property name="nextMessage" column="NEXT_MESSAGE_ID" type="long"/> </class> CRUD Operations… Map<String, Object> msg3 = new HashMap<String, Object>(); msg3.put("id", 1l); msg3.put("text", "Meeting canceled."); session.persist(msg3); © Onkar Deshpande
  • 29. Xml format for CRUD operations Mapping…. <class entity-name="employee" table="Emp" node="employee"> <id name="empId" type="int" column="EMPNO" node="empId"> <generator class="native"/> </id> <property name="name" type="string" node="name"> <column name="ENAME"/> </property> <property name="salary" type="float" node="salary"> <column name="SAL"/> </property> </class> CRUD Operations… Session dom4jSession = session.getSession(EntityMode.DOM4J); Element emp = (Element)dom4jSession.load("Employee", 7499); System.out.print(emp.elementText("empId")); System.out.print("t" + emp.elementText("name")); System.out.println("t" + emp.elementText("salary")); © Onkar Deshpande
  • 30. Module 4. Some mapping clauses  Overview  The paradigm mismatch- OOPs Vs. RDBMS  Hibernate built-in data types  Bypassing properties  Formula field  Making field-class immutable  Making field not-null  The object identity  Key auto-generation  Composite keys. © Onkar Deshpande
  • 31. Built-in mapping types. Mapping type Java type Standard SQL type integer int or java.lang.integer INTEGER long long. Or java.lang.Long BIGINT short short or java.lang.Short SMALLINT float float or java.lang.Float FLOAT double double or java.lang.Double DOUBLE big-decimal java.math.BigDecimal NUMERIC character java.lang.String CHAR string java.lang.String VARCHAR byte byte or java.lang.Byte TINYINT boolean boolean or java.lang.Boolean BIT yes_no boolean or java.lang.Boolean CHAR(1) true_false boolean or java.lang.Boolean CHAR(1) © Onkar Deshpande
  • 32. Built-in mapping types. Mapping type Java type Standard SQL type date java.util.Date or java.sql.Date DATE time java.util.Date or java.sql.Time TIME timeStamp java.util.Date or java.sql.TimeStamp TIMESTAMP calendar java.util.Calendar TIMESTAMP calendar_date java.util.Calendar DATE binary byte[] VARBINAR OR BLOB text java.lang.String CLOB Serializable Any serializable class VARBINAR OR BLOB Clob java.sql.Clob CLOB blob java.sql.Blob BLOB © Onkar Deshpande
  • 33. Mapping metadata Mapping… <class name="com.hibernate.pack50_moremappings.Emp" table="EMP" mutable="true" dynamic-update="true"> <id name="empNo" column="EMPNO" access="field"> <generator class="assigned"/> </id> <property name="eName" column="ENAME" access="field" not-null="true" /> <property name="sal" column="SAL" access="field" /> <property name="job" column="JOB" access="field" /> <property name="comm" column="COMM" access="field" /> <property name="deptNo" column="DEPTNO" access="field" /> <property name="totalSal" type="float" formula="SAL+COMM"/> </class> © Onkar Deshpande
  • 34. Mapping metadata <class name=“pack50_moremappings.Emp" table="EMP“ > <id name="empNo" column="EMPNO" > <generator class="assigned"/> </id> <property name="eName" column="ENAME" access="field" not-null="true" /> <property name="sal" column="SAL" insert="false" update="false"/> <property name="job" column="JOB" /> <property name="comm" column="COMM" /> <property name="totalSal" type="float“ formula="SAL + COMM" /> </class> © Onkar Deshpande
  • 35. Mapping metadata (Contd...)  Bypassing setter method for populating field with value.  <property name="eName" access="field“/> <!-- default is access=“property”->  Accessing derived properties.  <property name="totalSal" type="float“ formula="SAL + COMM" />  Avoiding trip to database if not-null field value is null.  <property name=" eName” not-null=“true” />  Controlling insertion and updation of a field.  <property name="sal" column="SAL" insert="false" update="false"/> © Onkar Deshpande
  • 36. Mapping metadata  Importing package for all beans.  <hibernate-mapping package=“pack50_moremappings”>  Making a class immutable  <class name=“Emp" table="EMP" mutable=“false”>  To prevent unmodified property value in SQL-insert.  <class name=“Emp" table="EMP" dynamic-insert="true”/>  To prevent unmodified property value in SQL-update  <class name=“Emp" table="EMP" dynamic-update="true”/> © Onkar Deshpande
  • 37. Identifier generators Generator Description native Picks active identity generators depending upon the database. increment Hibernates auto-generation policy. assigned User given key value. identity Supports identity column. sequence Uses sequence policy of data base. hilo Uses high/low algorithm policy of data base. Declaration in mapping file… <id name="empNo" column="EMPNO" type="integer"> <generator class="increment"/> </id> © Onkar Deshpande
  • 38. Declaration in mapping file… <class name="Books" table="Books"> <composite-id name="compoKey" class="CompositeId"> <key-property name="bookId"> <column name="BookId" not-null="true" /> </key-property> <key-property name="titleId"> <column name="TitleId" not-null="true" /> </key-property> </composite-id> <property name="cost" /> </class> public static class CompositeId implements Serializable { private int bookId; private String titleId; public CompositeIdBooks(){} public String getTitleId() { …} public void setTitleId(String titleId) { … } public int getBookId() {… } public void setBookId(int bookId) { …} } Composite key The composite key Embedable © Onkar Deshpande
  • 39. Composite key (Contd...) The entity bean @ Entity public class Books { @Id @ EmbeddedId private CompositeIdBooks compoKey; private float cost; public Books(CompositeIdBooks compoKey, float cost){ this.compoKey = compoKey; this.cost = cost; } } Accessing entity using composite key… Books.CompositeIdBooks bookKey1 = new Books.CompositeIdBooks(3, "AB124"); Books book1 = new Books(bookKey1, 1236.00f); session.save(book1); © Onkar Deshpande
  • 40. Key equality.  Emp emp2 = (Emp) session.load( Emp.class, 7499 );  Emp emp3 = (Emp) session.load( Emp.class, 7499 ); System.out.println("Returning cached object:"+emp2.hashCode()+" "+emp3.hashCode());  System.out.println(session.getIdentifier(emp2));  System.out.println(session.getIdentifier(emp3)); © Onkar Deshpande
  • 41. Module 5. More mapping concepts  Overview  The paradigm mismatch- Granularity OOPs Vs. RDBMS  Matching fine-granularity  Matching objects’ inheritance structure with tables  Mapping collections of value type © Onkar Deshpande
  • 42. Granularity matching public class User { private int userId; private String userName; private Address billingAddress; private Address homeAddress; …………. } public class Address { private String street; private String city; private String pin; private User user; …………… } Table structure: USER_ID number(5) not null, USERNAME varchar2(15) not null, HOME_STREET varchar2(10), HOME_CITY varchar2(10), HOME_PIN varchar2(6), BILLING_STREET varchar2(10), BILLING_CITY varchar2(10), BILLING_PIN varchar2(6) © Onkar Deshpande
  • 43. Granularity matching (Contd...) Mapping… <class name="User" table="USERS"> <id name="id" column="USER_ID" type="integer"> <generator class="native"/> </id> <property name="userName" column="USERNAME" /> <component name="homeAddress" class="Address"> <parent name="user"/> // For bi-directional navigation. <property name="street“ column="HOME_STREET" /> <property name="city" column="HOME_CITY" /> <property name="pin“ column="HOME_PIN" /> </component> …… </class> Loading of object… User user = (User) session.load( User.class, 1 ); Navigation from User to Address to user: user.getBillingAddress().getUser().getUserName()); © Onkar Deshpande
  • 44. Mapping inheritance  Approaches to represent inheritance hierarchy…  Table per concrete class : Discards inheritance hierarchy and polymorphism  Table per class hierarchy: Enable polymorphism by de-normalizing relational model.  Table per sub class: Represents inheritance as a foreign key relationship. © Onkar Deshpande
  • 45. The inheritance hierarchy BankAccount -accNo : int -accNM : String -accBal : float SavingsAcc -isSalAcc : boolean CurrentAcc -crLimit : float © Onkar Deshpande
  • 46. Table per concrete class. BankAcc SavingsAcc CurrentAcc Table: CCSavings ACCNO number(4), ACC_NM varchar2(15), ACC_BAL number(8,2), IS_SALACC number(1), CONSTRAINT pk_accno_ccsavings PRIMARY KEY (ACCNO) Table: CCCurrent ACCNO number(4), ACC_NM varchar2(15), ACC_BAL number(8,2), CR_LIMIT number(8), CONSTRAINT pk_accno_cccurrent PRIMARY KEY (ACCNO) <class name="SavingsAcc" table="CCSavings"> <id name="accNo" column="ACCNO" type="integer"> …… <property name="accNm" column="ACC_NM" type="string" /> ……. </class> <class name="CurrentAcc" table="CCCurrent"> <id name="accNo" column="ACCNO" type="integer"> …… <property name="accNm" column="ACC_NM" type="string" /> ……. </class> © Onkar Deshpande
  • 47. One table with discriminator. BankAcc SavingsAcc CurrentAcc Table: CHAccounts ACCNO number(4), ACC_NM varchar2(15), ACC_BAL number(8,2), ACCTYPE varchar2(2), IS_SALACC number(1), CR_LIMIT number(8) CONSTRAINT pk_accno_CHAccounts PRIMARY KEY (ACCNO) <class name=“BankAcc" table="CHAccounts"> <id name="accNo" column="ACCNO" type="integer"> …… <discriminator column="ACCTYPE" type="string" not-null="true"/> <property name="accNm" column="ACC_NM" type="string" /> ……. <subclass name="SavingsAcc" discriminator-value="SA"> <property name="salAcc" column="IS_SALACC" type="boolean“/> </subclass> <subclass name="CurrentAcc" discriminator-value="CA"> <property name="crLimit" column = "CR_LIMIT" type="long”/> </subclass> © Onkar Deshpande
  • 48. Table with part Joins BankAcc SavingsAcc CurrentAcc Table: PJAccounts ACCNO number(4), ACC_NM varchar2(15), ACC_BAL number(8,2), ACCTYPE varchar2(2), IS_SALACC number(1), CONSTRAINT pk_accno_PJAccounts PRIMARY KEY (ACCNO) Table: PJCurrent CACCNO number(4), CR_LIMIT number(8), CONSTRAINT fk_bankAcc_pjcurrent FOREIGN KEY (CACCNO) REFERENCES PJAccounts(ACCNO) <class name=“BankAcc" table=“PJAccounts"> <id name="accNo" column="ACCNO" type="integer"> …… <discriminator column="ACCTYPE" type="string"/> <property name="accNm" column="ACC_NM" type="string" /> ……. <subclass name="SavingsAcc" discriminator-value="SA"> <property name="salAcc" column="IS_SALACC" type="boolean“/> </subclass> <subclass name="CurrentAcc" discriminator-value="CA"> <join table="PJCurrent"> <key column="CACCNO"></key> <property name="crLimit" column = "CR_LIMIT" type="long“/> </join> </subclass> ….. © Onkar Deshpande
  • 49. Table with subclass joins BankAcc Table: SCCurrent CACCNO number(4), CR_LIMIT number(8), CONSTRAINT fk_bankAcc_Sccurrent FOREIGN KEY (CACCNO) REFERENCES SCAccounts(ACCNO) SavingsAcc CurrentAcc Table: SCAccounts ACCNO number(4), ACC_NM varchar2(15), ACC_BAL number(8,2), CONSTRAINT pk_accno PRIMARY KEY (ACCNO) Table: SCSavings SACCNO number(4), IS_SALACC number(1), CONSTRAINT fk_bankAcc_Scsaving FOREIGN KEY (SACCNO) REFERENCES SCAccounts(ACCNO) <class name="SavingsAcc" table="CCSavings"> <id name="accNo" column="ACCNO" type="integer"> …… <property name="accNm" column="ACC_NM" type="string" /> ……. <joined-subclass name="SavingsAcc" table="SCSavings"> <key column="SACCNO“/> // Primary / Foreign key. <property name="salAcc" column="IS_SALACC" type="boolean“/> </joined-subclass> <joined-subclass name="CurrentAcc" table="SCCurrent"> <key column="CACCNO“/> // Primary / Foreign key. <property name="crLimit" column = "CR_LIMIT" type="long“/> </joined-subclass> …… © Onkar Deshpande
  • 50. ITEM ITEMID Number(3) NAME Varchar2(15) 1 Almirah 2 Sofa 3 Tea top 4 Cane chair Primary Key: ITEMID Collections  In some online shopping web site, an item may be displayed by showing multiple images. To represent items, there should be a table holding multiple item entities. For each item entity, there can be one or more images.  The Item bean should have multiple references to ItemImage. These multiple references can be in the form of TreeSet, HashSet, ArrayList, HashMap, LinkedHashMap, TreeMap. © Onkar Deshpande
  • 51. Collections  Set: A collection of unique entities. There are two implementations…  TreeSet: An ordered collection of unique entities.  HashSet: An un-ordered collection of unique entities.  Bag: An un-ordered collection of may be duplicate entities. There is no equivalent of it in Java.  List: An ordered collection of entities. Here order specifies the order of adding entities in collection. It allows duplicates.  Map: An un-ordered collection of Key-Value pairs. It has different implementations like… HashMap. LinkedHashMap, TreeMap etc. © Onkar Deshpande
  • 52. ITEM ITEMID Number(3) NAME Varchar2(15) 1 Almirah 2 Sofa 3 Tea top 4 Cane chair Primary key: ITEMID ITEM_IMAGES ITEMID Number(3) FILENAME Varchar2(15) 1 Almira image1 1 Almira image2 1 Almira image3 3 Tea top image1 3 Tea top image2 4 Chair image3 FK: ITEMID on ITEMID of ITEM Collections: Using Set public class Item { private int itemId; private String itemName; Set<String> images; …. } item.hbm.xml… <set name="images" lazy="true" table="ITEM_IMAGES" sort="natural"> <key column="ITEMID"/> <element type="string" column="FILENAME" not-null="true"/> </set> © Onkar Deshpande
  • 53. ITEM ITEMID Number(3) NAME Varchar2(15) 1 Almirah 2 Sofa ITEM_IMAGES ITEM_IMAGES_SK (Num(3)) ITEMID Num(3) FILENAME Varchar2(15) 1 1 Almira image1 2 1 Almira image1 3 1 Almira image1 4 3 Tea top image1 5 3 Tea top image1 6 4 Chair image3 FK: ITEMID on ITEMID of ITEM Collections: Using Bag public class Item { private int itemId; private String itemName; List<String> images; …. } item.hbm.xml… <idbag name="images" lazy="true" table="ITEM_IMAGES_SK"> <collection-id type="int" column="ITEM_IMAGES_SK"> <generator class="increment"/> </collection-id> <key column="ITEMID"/> <element type="string" column="FILENAME" not-null="true"/> </idbag> © Onkar Deshpande
  • 54. ITEM ITEMID Number(3) NAME Varchar2(15) 1 Almirah 2 Sofa ITEM_IMAGES ITEMID Num(3) POSITION FILENAME Varchar2(15) 1 0 Almira image1 1 1 Almira image1 1 2 Almira image1 3 0 Tea top image1 3 1 Tea top image1 4 0 Chair image3 FK: ITEMID on ITEMID of ITEM Collections: Using List public class Item { private int itemId; private String itemName; List<String> images; …. } item.hbm.xml… <list name="images" lazy="true" table="ITEM_IMAGES_POSI"> <key column="ITEMID"/> <index column="POSITION"/> <element type="string" column="FILENAME" not-null="true"/> </list> © Onkar Deshpande
  • 55. ITEM ITEMID Number(3) NAME Varchar2(15) 1 Almirah 2 Sofa ITEM_IMAGES ITEMID Num(3) IMAGENAME (varchar2(15)) FILENAME Varchar2(15) 1 FrontView Almira image1 1 SideView Almira image1 1 InnerView Almira image1 3 FrontView Tea top image1 3 SideView Tea top image1 4 FrontView Chair image3 public class Item { private int itemId; private String itemName; Map<String, String> images; FK: ITEMID on ITEMID of ITEM …. } item.hbm.xml… <map name="images" lazy="true" table="ITEM_IMAGES_MAP“ sort=“natural”> <key column="ITEMID"/> <index column="IMAGENAME" type="string"/> <element type="string" column="FILENAME" not-null="true"/> </map> Collections: Using Map © Onkar Deshpande
  • 56. Module 6. The Association relations  Overview  The paradigm mismatch Association-OOPs and RDBMS  The Association-Multiplicity-Navigation  Understanding uni/bi-directional relationship  The One-One relationship  The One-many relationship  The Many-Many relationship  The Cascade clauses © Onkar Deshpande
  • 57. The Association One to One Multiplicity Emp Profile 1 1 One to Many Multiplicity Emp Department 0...* 1 Many to Many Multiplicity Emp Project 0…* 0…* © Onkar Deshpande
  • 58. The Association: One to One public class Emp { One to One Multiplicity Emp Profile 1 1 private Integer empNo; private String eName; private String job; // One to one towards Profile private Profile profile; // Association scaffolding code public Profile getProfile() { return profile; } public void setProfile(Profile profile) { this.profile = profile; } } public class Profile { private int empId; private String skills; private String quali; // One to one towards emp private Emp emp; // Association scaffolding code public Emp getEmp() { return emp; } public void setEmp(Emp emp) { this.emp = emp; } } © Onkar Deshpande
  • 59. The Association: One to One (Contd...) <class name="Emp" table="EMP"> <id name="empNo"> …… <property name="eName"> …… <one-to-one name="profile" // Name of setter method which executes association in Emp class="Profile" // Name of a class of object which is being associated with Emp. foreign-key="empId"// Name of a property in Profile which represents foreign key for Emp /> </class> <class name="Profile" table=“PROFILES"> <id name="empId"> ….. <property name="skills"> ….. <!-- For bi-directional navigation. --> <one-to-one name="emp" // Name of a setter method which establishes association in Profile class="Emp"// Name of a class of object which is being associated with Emp. property-ref="profile" // Name of a property in Emp which establishes Emp -> Profile relation. /> </class> © Onkar Deshpande
  • 60. Cascade options Cascade Description none To ignore association save-update Persist transient object and all associated objects. Update association graph. delete Delete all associated persistent instances. all Cascade save-update, delete and evict and lock. all-delete-orphan Like cascade all + deletes all de-referenced objects also. delete-orphan Deletes all de-referenced objects also. Declaration in mapping file… <!-- cascade="save-update" cascade=“delete"--> <one-to-one name="profile“ class="Profile" foreign-key="empId" cascade=“save-update" /> © Onkar Deshpande
  • 61. The Association: One to Many public class Emp { One to Many Multiplicity Emp Department 0…* 1 private Integer empNo; private String eName; private String job; // One to one towards Profile private Profile profile; // Association scaffolding code public Profile getProfile() { return profile; } public void setProfile(Profile profile) { this.profile = profile; } } public class Dept { private int deptNo; private String deptNm; private Set<Emp> emps; // One to Many // Association scaffolding code public Set<Emp> getEmps(){ return emps; } public void setEmps(Set<Emp> emps){ this.emps = emps; } public void addEmps(Emp emp){ emp.setDepartment(this); emps.add(emp); } } © Onkar Deshpande
  • 62. The Association: One to Many (Contd...) <hibernate-mapping package="com.hibernate.pack90_association.pack20_oneMany"> <class name="Emp" table="EMP"> <id name="empNo" column="EMPNO" length="4"> <generator class="assigned" /> </id> <property name="eName" column="ENAME" length="15" /> <property name="job" column="JOB" length="10" /> <many-to-one name="department" column="DEPTNO" class="Dept" not-null="true" /> <!-- lazy="false" --> </class> </hibernate-mapping> © Onkar Deshpande
  • 63. The Association: Many to Many Many to Many Multiplicity Emp Project 0…* 0…* public class Emp { private Integer empNo; private String eName; private String job; // Many to many towards Project private Set<Project> projects; // Association scaffolding code public void setProjects(Set projects){ this.projects = projects; } public Projects getProjects(){ return projects; } } public class Project { private Integer projectId; private String projectTitle; // Many to Many towards Emp private Set<Emp> emps; // Association scaffolding code public Set<Emp> getEmployees() { return emps; } public void setEmployees(Set emps) { this.emps = emps; } } © Onkar Deshpande
  • 64. The Association: Many to Many (Contd...) <class name="Project" table="PROJECT"> <id name="projectId" column="PROJECTID"> ….. <property name="projectTitle" column="TITLE" /> <!-- Many to Many --> <set name="employees“ table=" EMP_PROJECT "> <key column="PROJECTID" /> <many-to-many class="Emp" column="EMPNO" /> </set> </class> <class name="Emp" table="EMP"> <id name="empNo" column="EMPNO" length="4"> ……. <property name="eName" column="ENAME" length="15" /> <property name="job" column="JOB" length="10" /> <!-- Many to Many --> <set name="projects“ table=" EMP_PROJECT "> <key column="EMPNO" /> <many-to-many class="Project" column="PROJECTID" /> </set> </class> © Onkar Deshpande
  • 65. Module 7. Hibernate Transaction support  Overview  Local and global transactions  Transactions in JDBC  Transactions in Hibernate  Transactions in non-managed and managed environments  Hibernate transaction API  JTA and Container Managed Transaction.(CMT)  Concurrency, locks and Isolation levels © Onkar Deshpande
  • 66. Transaction Automatic steps Step 1---------------- Step 2---------------- Step 3---------------- Step 4---------------- Step 5---------------- Step 6---------------- Step 7---------------- If any one step is un-successful: Do nothing “Rollback” Only if all steps are successful: Persist state of all commands Commit Database © Onkar Deshpande
  • 67. Local transaction  One service within a single program accessing single database.  Transactions confined to objects residing in one particular JVM.  The JDBC transaction on a connection is Local. Automatic steps Step 1---------------- Step 2---------------- Step 3---------------- Step 4---------------- Step 5---------------- Step 6---------------- Step 7---------------- Database © Onkar Deshpande
  • 68. Global transaction  Transaction encapsulating object which are distributed on various JVMs.  Transactions on more than one resource managers where these managers are running on different servers.  A transaction with more than one databases. Automatic steps Step 1---------------- Step 2---------------- Step 3---------------- Step 4---------------- Step 5---------------- Database Database Server/JVM Server/JVM © Onkar Deshpande
  • 69. Transaction in JDBC. To start a transaction bound to the connection. connection.setAutoCommit(false); To commit a transaction: connection.commit(); To roll back a transaction: connection.rollback(); Alternatives for ending transaction: 1. setAutoCommit to true if set to false previously. 2. Commit a transaction 3. Rollback a transaction 4. If timeout occurs, transaction rollsback. Local transactions can be turned off by adding following property to URL... disableLocalTxn=true © Onkar Deshpande
  • 70. Transaction in Hibernate  Hibernate supports..  JDBC transaction in non-managed environment  JTA transaction in managed environment.  Non-managed environment  An environment, data source is not provided as a ready resource. Ex. JDBC.  The managed environment  The environment manages connection, its pool and the data source. Servers (Web or appl) provide managed environments.  The Java Transaction API (JTA):  Manages distributed transaction  Allows declarative transaction  Supports Container Managed Transaction (CMT) © Onkar Deshpande
  • 71. Hibernate Transaction API <interface> Transaction CORBATransaction JDBCTransaction JTATransaction © Onkar Deshpande
  • 72. Hibernate Transaction API  session.beginTransaction():  In non-managed environment: Starts a new JDBC transaction.  In managed environment: Starts new JTA transaction.  begin(): Starts a new transaction  commit(): Synchronizes session state with database.  rollback(): Forces underlying transaction to roll back.  isActive(): Is this transaction still active?  wasCommitted(): Check if this transaction was successfully committed.  wasRolledBack(): Was this transaction rolled back or set to roll back?  setTimeOut(int timeInSeconds): Sets the transaction time out. © Onkar Deshpande
  • 73. Trasactional Attributes  Required  RequiresNew  Mandatory  Supports  NotSupported  Never © Onkar Deshpande
  • 74. Transactional Attributes The Required (Default) attribute The declared method must be invoked within the scope of the transaction. Client (T1) T1 Client T1 Runs in propagated transaction T1 Runs in New transaction T1 The RequiredNew attribute The declared method must be invoked always in new transaction. Client (T1) T1 Client T1 Runs in propagated transaction T1 Runs in New transaction T1 © Onkar Deshpande
  • 75. Transactional Attributes The Supports attribute The declared method is included in transaction scope if invoked within a transaction. Client (T1) T1 Client Method Runs in propagated transaction T1 Runs without transaction The NotSupported attribute The declared method when invoked within transaction scope, suspends transaction until method completes Client (T1) Method Runs without transaction © Onkar Deshpande
  • 76. Transactional Attributes The Mandatory attribute The declared method is included in transaction scope if invoked within a transaction Client (T1) T1 Client Method Runs in propagated transaction T1 Throws exception when run without transaction. The Never attribute The declared method must never be invoked in any Client (T1) T1 Client Method Throws exception when run within transaction Runs without transaction © Onkar Deshpande
  • 77. Isolation Issues  Lost update  Dirty read  Unrepeatable read  Second lost update  Phantom read © Onkar Deshpande
  • 78. Isolation Levels Isolation levels and their values Read Uncommitted 1 Read Committed 2 Repeatable Read 4 Serializable 8  Every JDBC connection uses database default value of isolation.  Explicit setting of isolation level can be done by introducing following entry into cfg file.  hibernate.connection.isolation=2 © Onkar Deshpande
  • 79. Locking  A mechanism that prevents concurrent access to the particular item of data.  A transaction has to acquire a lock for reading or modifying the item.  Types of locks:  Pessimistic  Optimistic © Onkar Deshpande
  • 80. Pessimistic Locks  It is acquired when item of data is read and held until transaction is completed.  Some databases allow locking with Select – For Update clause.  Hibernate’s different lock modes...  LockMode.NONE  LockMode.READ  LockMode.UPGRADE  LockMode.UPGRADE_NOWAIT  Category cat = (Category) session.get(Category.class, catId, LockMode.UPGRADE);  It loads category with Select…For Update and locks the retrieved row until transaction ends. © Onkar Deshpande
  • 81. Pessimistic Locks  Except NONE all lock modes makes hibernate to go to DB.  The load() and get() by default uses LockMode.NONE.  The LockMode.READ needs on detached object with lock() to check version of corresponding row.  The LockMode.UPGRADE locks a row at DB side thereby hampering scalability.  The strict locking at application side hampers performance of other applications. © Onkar Deshpande
  • 82. Optimistic Locks An additional column in table for Version or TimeStamp managed automatically by hibernate every time object is modified public class Item { ------- int version; public int getVersion(){ return version; } public void setVersion(int v){ this.version = v; } OR Date timeStamp; public void setLastUpdateDateTime(Date dt){ this.timeStamp = dt; } public Date getLast… } <class name=“item” table=“ITEM”> <id>…</id> <version name=“version” column=“VERSION” /> </class> OR <class name=“item” table=“ITEM”> <id>…</id> <timestamp name=“lastUpdateDateTime” column=“UPDATE_DATE” /> </class> © Onkar Deshpande
  • 83. Module 8. Queries in Hibernate  Overview  Object retrieving  Why HQL?  Working with HQL  Working with Native queries  Working with Criteria queries © Onkar Deshpande
  • 84. Retrieving Objects  Navigating object graph.  aUser.getAddress().getCity()  Retrieving by identifier.  User user = (User) session.get(User.class, userId);  Using Hibernate Query Language (HQL)  String qry = “from Emp e order by e.job asc, e.sal desc”;  List<Emp> empList = session.createQuery(qry );  Using Criteria API  Criterion restriction = Expression.eq("empNo", 7499);  Emp emp = (Emp) session.createCriteria(Emp.class).add( restriction ).uniqueResult();  Using Query By Example (QBE)  QueryOnEmp queryByExample = new QueryOnEmp();  queryByExample.seteName("J%");  queryByExample.setJob("MANAGER");  String queryString_HQL = "from Emp emp where emp.eName like :ename and emp.job like :job";  List<Emp> emps = session.createQuery(queryString_HQL).setProperties(queryByExample).list();  Using Native Query Language (NQL)  String qry = “select {i.*} from EMP {i} order by JOB asc, SAL desc”;  List<Emp> empList = session.createSQLQuery(qry ); © Onkar Deshpande
  • 85. Hibernate Query Language  Query to get all employees from table.  Query qryForAllEmployees = session.createQuery("from Emp");  List<Emp> empList = qryForAllEmployees.list();  Query to get objects in pages in given order.  String qry = “from Emp e order by e.job asc, e.sal desc”;  Query qryForAllEmployees = session.createQuery(qry);  qryForAllEmployees.setFirstResult(0);  qryForAllEmployees.setMaxResults(5);  List<Emp> empList = qryForAllEmployees.list();  Query for unique result. Using positional parameters, Binding parameters  Emp emp = (Emp) session.createQuery("from Emp e where e.empNo = ?").setInteger(0, 7499).uniqueResult();  Query for list with named parameters  List<Emp> empList = session.createQuery("from Emp e where e.eName like :name").setString( “A%”, eName,).list(); © Onkar Deshpande
  • 86. Hibernate Query Language (Contd...)  Query for property value ‘null’  List<Emp> emps = session.createQuery("from Emp as e where e.mgr is null").list();  Query with between clause  Query qryForAllEmployees = session.createQuery("from Emp where empNo between :vl1 and vl2").setInteger(“vl1”, 7500).setInteger(“vl2”, 8000);  Query with ‘in’ clause…  from Emp where empNo in (7369, 7499)  Query with logical operators  from Emp where eName like :name And job like :job  from Emp where eName like :name Or job like :job.  Writing group queries.  select count(*) from Emp  select sum(sal) from Emp © Onkar Deshpande
  • 87. Criteria Queries  Criteria for all employees  Criteria qryForAllEmployees = session.createCriteria(Emp.class);  List<Emp> empList = qryForAllEmployees.list();  Criteria to get objects in pages in given order.  List<Emp> empList = session.createCriteria(Emp.class)  .addOrder( Order.asc("job") )  .addOrder( Order.desc("sal"))  .setFirstResult(0)  .setMaxResults(5)  .list();.  Criteria for unique result. Binding parameters  Criterion restriction = Expression.eq("empNo", 7499);  Emp emp = (Emp) session.createCriteria(Emp.class).add( restriction ).uniqueResult();  Criteria for list with named parameters  List<Emp> empList = session.createCriteria(Emp.class)  .add(Expression.ilike("J%“, "eName")).list(); © Onkar Deshpande
  • 88. Criteria Queries (Contd...)  Criteria with restriction on value ‘null’  List<Emp> emps = session.createCriteria(Emp.class).add(Expression.isNull("mgr")).list();  Criterion for between and in clauses.  Criterion restriction = Expression.between("empNo", 7800, 7900);  Criterion restriction = Expression.in("empNo", new Object[]{7369, 7499});  Criteria query with logical operators- And  Criterion restriction1 = Expression.like("eName", "J%");  Criterion restriction2 = Expression.like("job", "MANAGER");  List<Emp> empList = session.createCriteria(Emp.class)  .add(restriction1)  .add(restriction2)  .list();  Criteria with restriction with complex boolean expression.  Criterion restriction1 = Expression.like("eName", "J%");  Criterion restriction2 = Expression.like("job", "MANAGER");  Criterion restriction3 = Expression.or(restriction1, restriction2);  Criterion restriction4 = Expression.gt("sal", 2500f);  Criterion restriction5 = Expression.and(restriction3, restriction4);  List<Emp> empList = session.createCriteria(Emp.class)  .add(restriction5)  .list(); © Onkar Deshpande
  • 89. Native Query Language  Query to get all employees from table.  SQLQuery qryForAllEmployees = session.createSQLQuery("select {i.*} from EMP {i}");  List<Emp> empList = qryForAllEmployees.addEntity("i", Emp.class).list()  Query to get objects in pages in given order.  String qry = “select {i.*} from EMP {i} order by JOB asc, SAL desc"  List<Emp> empList= session.createSQLQuery(qry )  .addEntity("i", Emp.class)  .setFirstResult(0)  .setMaxResults(5).list();  Query for unique result. Using positional parameters, Binding parameters  String qry = “select {i.*} from EMP {i} where EMPNO like ?"  Emp emp = (Emp) session.createSQLQuery(qry )  .addEntity("i", Emp.class)  .setInteger(0, 7499).uniqueResult(); © Onkar Deshpande
  • 90. Native Query Language (Contd...)  Query for list with named parameters  String qry = “select {i.*} from EMP {i} where EMPNO like :empNo”;  Emp emp = (Emp) session.createSQLQuery(qry)  .addEntity("i", Emp.class)  .setInteger("empNo", 7499).uniqueResult();  Query for property value ‘null’  select {i.*} from EMP {i} where MGR is null  Query with between and in clause  select {i.*} from EMP {i} where EMPNO between :val1 and :val2  select {i.*} from EMP {i} where EMPNO in (:val1, :val2) © Onkar Deshpande
  • 91. Module 9. Advanced queries  Overview  Query by example  Named queries  Report queries  Fetching strategies and joins © Onkar Deshpande
  • 92. Query by example public class QueryOnEmp { private String ename; private String job; public String geteName() { return ename; } public void seteName(String ename) { this.ename = ename; } public String getJob() { return job; } public void setJob(String job) { this.job = job; } } QueryOnEmp queryByExample = new QueryOnEmp(); queryByExample.seteName("J%"); queryByExample.setJob("MANAGER"); © Onkar Deshpande
  • 93. Report Queries  Projection with Object array String qry = "select emp.empNo, emp.eName, emp.sal from Emp emp"; Iterator i = session.createQuery(qry) list().iterator(); while ( i.hasNext() ) { Object[] row = (Object[]) i.next(); Integer empNo = (Integer) row[0]; String eName = (String) row[1]; Float sal = (Float) row[2]; System.out.println("Number:"+empNo+"tName:"+eName+"tSal:"+sal); }  Projection with dynamic instantiation. String qry = "select new EmpRow(e.empNo, e.eName, e.sal) from Emp e"; Iterator i = session.createQuery(qry).list().iterator(); while ( i.hasNext() ) { EmpRow emp = (EmpRow) i.next(); System.out.println(emp); } © Onkar Deshpande
  • 94. Named Queries 1. A technique to externalize query. 2. All queries to be accumulated in separate XML file. 3. The code is not cluttered up with queries. 4. Code identifies queries using their unique names. <!-- Named Queries --> <query name="findEmpsByName-HQL"> <![CDATA[from Emp emp where emp.eName like :name]]> </query> <sql-query name="findEmpsByName-SQL"> <![CDATA[select {i.*} from EMP {i} where ENAME like :name]]> <return alias="i" class="Emp"/> </sql-query> List<Emp> empList = session.getNamedQuery("findEmpsByName-SQL") .setString("name", "J%").list(); List<Emp> empList = session.getNamedQuery("findEmpsByName-HQL") .setString("name", "J%").list(); © Onkar Deshpande
  • 95. Joins  Inner Joins: All items that have bids  Left outer Joins: All items with their bids and also items without bids.  Right Joins: All items with their bids and all bids which are not on any item (Not applicable here).  Theta style joins:  Implicit Joins Uses multiple property paths for expressing implicit associations or querying components. Item Bid bids //Setter //getter Bid Item item //Setter //getter 1 0..* © Onkar Deshpande
  • 96. Joins Inner Joins Select bid from Bid bid inner join bid.item OR Select bid from Bid bid join bid.item select i.name, b.bid_id, from Bids b join Items i on i.item_id = b.item_id Outer Joins: Select bid from Bid bid left join fetch bid.item Select bid from Bid bid left outer join bid.item Select bid from Bid bid right outer join bid.item; select i.name, b.bid_id, from Bids b left join Items i on i.item_id = b.item_id select i.name, b.bid_id, from Bids b right join Items i on i.item_id = b.item_id © Onkar Deshpande
  • 97. Joins Implicit Joins Select bid from Bid bid where bid.item.itemId!=1 Select bid from Bid bid where bid.item.itemId is null select i.name, b.bid_id from Bids b join Items i on i.item_id = b.item_id where i.item_id is null; Implicit Joins Select bid from Bid bid where bid.item.itemId!=1 Select bid from Bid bid where bid.item.itemId is null Theta style Joins: Select i.name, b.bidId from Item i, Bid b where bid.bidId > 5 from Item, Bid // Gives Cartesian product Criteria doesn’t provide Theta style joins and Cartesian product. Hibernate does not support outer join on two tables which are not associated. © Onkar Deshpande
  • 98. Fetching Types of fetching • Immediate • Lazy • Eager • Batch • Its normal practice to define lazy fetching in mapping files. • In the code, ‘fetch’ keyword overrides lazy fetching. Thus code decides the fetching strategy. select i.name, b.bid_id, from Bids b join fetch Items i on i.item_id = b.item_id select i.name, b.bid_id, from Bids b left join fetch Items i on i.item_id = b.item_id select i.name, b.bid_id, from Bids b right join fetch Items i on i.item_id = b.item_id © Onkar Deshpande
  • 99. Module 10. More on Hibernate  Overview  Automating naming conventions.  Dynamic alterations to context  Connection pooling  Hibernate in web application  Building database structure through Mapping files.  Caching support in Hibernate.  Using Log4J with Simple Logger Facad.  Hibernate in Spring © Onkar Deshpande
  • 100. Naming Convensions The emb.hbm.xml <class name="Emp"> <id name="empNo" > <generator class="assigned"/> </id> <property name="eName" /> <property name="sal" l/> ……. </class> Building Session SessionFactory sessions = new Configuration() .configure(relativePathToConfig) .setNamingStrategy( new PRConvensions() ) .buildSessionFactory(); Code referring Emp Query queryForEmps = session.createQuery("from Emp"); List<Emp> empList = queryForEmps.list(); for(Emp emp : empList){ System.out.println(emp); } © Onkar Deshpande
  • 101. Naming Convensions (Contd...) public class PRConvensions implements NamingStrategy { private String className; public String tableName(String tableName) { return "PR_" + tableName; } public String classToTableName(String className) { this.className = StringHelper.unqualify(className).toUpperCase(); return tableName( this.className ); } public String propertyToColumnName(String propertyName) { return className+"_"+propertyName.toUpperCase(); } public String propertyToTableName(String className, String propertyName) { return classToTableName(className) + '_' +propertyToColumnName(propertyName); } public String columnName(String columnName) { return "PR_"+columnName; } © Onkar Deshpande
  • 102. Dynamic Context manipulation Configuration cfg = new Configuration().configure(relativePathToConfig); // Get the existing mapping for User from Configuration PersistentClass userMapping = cfg.getClassMapping("pack950_moreHiber.pack20_dynaMetadata.Emp"); // Define a new column for the EMP table Column column = new Column(); column.setSqlType("varchar2"); column.setName("EMP_MOTTO"); column.setNullable(true); column.setUnique(false); Table table = userMapping.getTable(); able.addColumn(column); // Wrap the column in a Value SimpleValue value = new SimpleValue(null, null); value.setTable( userMapping.getTable() ); value.addColumn(column); value.setTypeName("string"); // Define a new property of the User class Property prop = new Property(); prop.setValue(value); prop.setName("motto"); prop.setNodeName("motto"); userMapping.addProperty(prop); © Onkar Deshpande
  • 103. Connection Pooling Why Connection pools? • Acquiring new connection is expensive • Maintaining many idle connections is expensive • Creating prepared statements for some drivers is expensive What is connection pool? • Holds live connections. On demand supply them. • Can automatically change pool size as per utilization of connections. • Provides utmost scalability of connections. • The DriverManager manages connections. In managed environment Connection pools and Driver Manager are created by environment and provided as a service to all applications running under environment. In non-managed environment The third party tool can be used to avail feature. Hibernate has inbuilt support for C3P0. Hibernate Configuration… <property name="hibernate.c3p0.min_size">5</property> <property name="hibernate.c3p0.max_size">20</property> <property name="hibernate.c3p0.timeout">300</property> <property name="hibernate.c3p0.max_statements">50</property> <property name="hibernate.c3p0.idle_test_period">3000</property> © Onkar Deshpande
  • 104. Hibernate in web application The SessionFactory: It is thread safe and cluster safe. Heavy weight. Should be created once in an application. The Session: Not thread safe. Execute its instance in single thread. Light weight, should be created and destroyed in a method or for a request. The PersistentUtil private static final SessionFactory sessionFactory; // To create once // Session and transaction for each request. private static final ThreadLocal<Session> threadSession = new ThreadLocal<Session>(); private static final ThreadLocal<Transaction> threadTransaction = new ThreadLocal<Transaction>(); © Onkar Deshpande
  • 105. Hibernate in web application Getting a session: Session session = sessionFactory.openSession(); threadSession.set(session); Getting Transaction: Transaction transaction = session.beginTransaction(); threadTransaction.set(transaction); Committing or Rolling back Transaction Transaction tx = threadTransaction.get(); if ( tx != null && !tx.wasCommitted() && !tx.wasRolledBack() ) { tx.commit(); / tx.rollBack(); threadTransaction.set(null); } Closing Session Session session = (Session) threadSession.get(); threadSession.set(null); if (session != null && session.isOpen()) session.close(); © Onkar Deshpande
  • 106. Table structure from mapping files.  Its an approach of development where entities are identified as classes and from mapping file, Hibernate creates a table structure with all necessary associations and inheritance.  Hibernate does not support creating classes from table structure (iBatis supports).  The cfg file.  <property name="hibernate.hbm2ddl.auto">update</property>  If hibernate finds that table is existing but with mismatch in fields with table, columns are altered in table. © Onkar Deshpande
  • 107. Caching support in Hibernate.  There are two levels of caching…  Transactional Cache/First level cache provided by Hibernate Session.  Global Cache/Second level cache provided by Cache provider.  All transient objects are entitled for caching.  By default hibernate queries always ignore cache.  If second level cache is enabled, FLC contents are written to SLC.  The query is cached only if it is explicitly cached.  To explicitly cache query, Query interface has method setCacheable();  The SessionFactory has special API to view IInd level cache statistic. © Onkar Deshpande
  • 108. Caching support in Hibernate.  Enabling IInd level cache.  hibernate.cache.use_second_level_cache = true  hibernate.cache.use_query_cache = true  hibernate.cache.provider_class = et.sf.hibernate.cache.QueryCache  Third party IInd level cache.  EhCache, TerraCota, TreeCache, SwarmCache, oscache © Onkar Deshpande

Editor's Notes

  • #2: 1
  • #4: 3
  • #6: Hibernate clients: Hibernate is intended to be used in just about any architectural scenario imaginable (as long as the application is written in Java). It might run inside a servlet engine—where you could use it with web application framework like Struts, Web-Work or Tapestry—or inside an EJB container, a Swing client, a lightweight container, or even a JMX server like JBoss. Each of these environments requires infrastructure to integrate Hibernate with the way requests, transactions, and database resources are managed. The Hibernate core provides optional components for certain common integration scenarios, including integration with JTA, JNDI-bound data-sources, JMX, JCA, and the transaction managers of all popular application servers. In addition, some frameworks like Spring and Keel ship with built-in Hibernate support, and plugin support is available for others including Tapestry, Apache Avalon, and PicoContainer. JBoss Application Server features special support for Hibernate archive deployment and integration of Hibernate as a JMX-managed component.
  • #9: Paradigm mismatch Problem of granularity: The SQL standard supports user defined data types but very poorly. The feature is not portable across different databases. Because of this reason, the UDT is not a common practice in the industry. At OOPs side, designers may design coarse grained entity class for employee having fields for address or fine grained entity class with separate class to represent Address like UDT. While at DB side, there may be single column of varchar type to hold all components of address. It turns out to be granularity problem where granularity at both sides is mismatching. The subtype problem: The OOPs paradigm has important feature of Inheritance where entities may be represented as super class and sub classes. There is no concept of inheritance in DB. The DB data may have inheritance data within single table or across more than one table. Problem of identity: The OOPs paradigm identifies two objects for equality on the basis of reference. The equality operator (==) and equivalence method equals() both may check equality on the basis of reference or natural/auxiliary comparison which may be different than equality policy a DB is implementing. DB implements equality policy on the basis of Primary key or surrogate key. The primary key or surrogate key may be system generated and used by DB for its internal purpose while this key may not be used by OOPs paradigm to identify objects. Problems relating to Association: The OOPs paradigm uses reference to associate two entities. It represents navigation as unidirectional or bidirectional. While at DB side, association between two entities is represented through foreign key. There is no notion of navigation in DB. Also, association in OOPs represents Many-Many relationship if entities at both side have collections to represent multiple references of each other. DB does not represent Many-Many relationship naturally. An additional mapping table is necessary to represent such types of relationships. The n+1 select problem: If entity user is associated with multiple entities of BillingDetails. Then in object design, while visiting every object in java, separate SQL is fired to populate the object. One SQL for user and N number of SQL for N records of BillingDetails. It is called as n + 1 select problem.
  • #10: 9
  • #11: 10
  • #12: 11
  • #13: 12
  • #14: 13
  • #15: 14
  • #16: 15
  • #17: 16
  • #18: 17
  • #20: 19
  • #21: 20
  • #22: 21
  • #23: 22
  • #24: 23
  • #25: 24
  • #26: 25
  • #27: 26
  • #28: 27
  • #29: 28
  • #30: 29
  • #31: 30
  • #32: 31
  • #33: 32
  • #34: 33
  • #35: 34
  • #36: 35
  • #37: 36
  • #38: 37
  • #39: 38
  • #40: 39
  • #41: 40
  • #42: 41
  • #43: 42
  • #44: 43
  • #45: 44
  • #46: 45
  • #47: (Source code: pack80_inherit.tbl01ForConcreteClass) Table per concrete class: There will be one table for each (non-abstract) class. All properties of a class, including inherited properties, could be mapped to columns of this table. The main problem with this approach is that it doesn’t support polymorphic associations very well. Can not obtain object of super class thus this case can not work with polymorphic queries. The super class fields are being repeated as columns in all subclass. Change in any super-class field size/type or constraint lead to manual change in all table structures. This strategy is recommended only if polymorphic accessing is not expected.
  • #48: (Source code: pack80_inherit.tbl02WithDiscriminator) One Table with discriminator: Mapping entire class hierarchy in to one table. This table includes all properties from all classes including super class and all its subclasses. The element <subclass> indicates table per class hierarchy mapping. The discriminator column identifies records of specific subclass. Gives performance and simplicity against loss of some valuable space on DB. It also gives good polymorphism at OOPs side. The ad-hoc reporting is possible without complex joins and sub-queries. When to use: If polymorphic association or polymorphic queries. Subclass having relatively few properties. Only one problem: The columns belonging to subclass must be declared 'nullable'. And thus subclass columns can not implement non-nullable constraint.
  • #49: (Source code: pack80_inherit. tbl03WithPartjoin) Table with part join: Creating one table for super and that/those subclasses with less number of columns and separate table for class with many number of columns. The separate subclass table/s are joined with super class table through FK. For BankAcc and SavingsAcc- table created is PJAccounts: The ACCNO has been declared as PK. For CurrentAcc- table created is PJCurrent: The CACCNO has been declared as foreign key towards ACCNO of PJAccounts. Hibernate creates complex query on joined table to handle situation. Thus this mapping strategy is difficult to implement by hand. The <subclass> indicates table per class hierarchy mapping. But this strategy is partly mixed with join. The <join> element indicates the foreign key joining. When to use: If polymorphic association or polymorphic queries. Some subclasses having relatively less number of columns while some may have many number of columns. For deep inheritance hierarchy, the performance may be un-compramising.
  • #50: (Source code: pack80_inherit. tbl04WithSubclassJoins) Table with sub class joins: Creating tables per class. The subclass tables are joined with super class table through FK. No discriminator is needed in this strategy. The primary advantage of this strategy is the relational model is completely normalized. Schema evolution and integrity definitions are straight forward. For BankAcc- table created is SCAccounts: The ACCNO has been declared as PK. For SavingsAcc- table created is SCSavings: The SACCNO has been declared as foreign key towards ACCNO of SCAccounts. For CurrentAcc- table created is SCCurrent: The CACCNO has been declared as foreign key towards ACCNO of SCAccounts. The <joined-subclass> maps subclass to a new table. The key columns specified is a foreign key declared in subclass table towards super class table. The properties declared are mapped with columns of subclass table. Hibernate creates complex query to handle situation. Thus this mapping strategy is difficult to implement by hand. When to use: If polymorphic association or polymorphic queries. Subclass having many properties. For deep inheritance hierarchy, the performance may be un-compromising. The <joined-subclass> may contain another <joined-subclass> element but not <subclass>. Hibernate does not allow mixing of these two strategies. Hibernate will use outer join when queried for BankAcc.
  • #51: 50
  • #52: 51
  • #53: 52
  • #54: 53
  • #55: 54
  • #56: 55
  • #57: 56
  • #58: 57
  • #59: 58
  • #60: 59
  • #61: 60
  • #62: 61
  • #63: 62
  • #64: 63
  • #65: 64
  • #66: 65
  • #67: 66
  • #68: 67
  • #69: 68
  • #71: 70
  • #73: 72
  • #75: Transactional Attributes Required:- If the client is running within a transaction and invokes the enterprise bean’s method ,the method executes within the client’s transaction. If the client is not associated with a transaction, the container starts a new transaction before running the method. RequiresNew:- If the client is running within a transaction, and invokes the enterprise bean’s method ,the container takes the following steps: Suspends the clients transaction Starts a new transaction. Delegates the call to the method Resumes the clients transaction after the method completes.
  • #76: Transactional Attributes Supports :- If the client is running within a transaction and invokes the enterprise bean’s method ,the method executes within the clients transaction. If the client is not associated with a transaction, the container does not start a new transaction before running the method. NotSupported :- If the client is not associated with a transaction, the container does not start a new transaction before running the method. Use the NotSupported attribute for methods that don’t need transactions. Because transactions involve overhead, this attribute may improve performance.
  • #77: Transactional Attributes Mandatory:- If the client is not associated with a transaction, the container throws the TransactionRequiredException. Use the Mandatory attribute if the enterprise bean’s method must use transaction of the client. Never :- If the client is running within a transaction and invokes the enterprise bean’s method, the container throws a RemoteException. If the client is not associated with a transaction ,the container does not star a new transaction before running the method.
  • #78: 77
  • #79: 78
  • #80: 79
  • #81: 80
  • #82: 81
  • #83: 82
  • #84: 83
  • #85: 84
  • #86: 85
  • #87: 86
  • #88: 87
  • #89: 88
  • #90: 89
  • #91: 90
  • #92: 91
  • #93: 92
  • #94: 93
  • #95: 94
  • #96: (Source code: pack920_joins)
  • #97: 96
  • #98: 97
  • #99: 98
  • #100: 99
  • #101: 100
  • #102: 101
  • #103: 102
  • #104: 103
  • #105: 104
  • #106: 105
  • #107: 106
  • #108: 107
  • #109: 108