Download as pdf or txt
Download as pdf or txt
You are on page 1of 52

Hibernate Training

-Gopal Patel

CONFIDENTIAL
 Hands on with methods provided by Session interface
 Save()
 Update()
 SaveOrUpdate()
 Get()
 Load()
 Lock()
 Delete()
 Use Lazy Initialization (Many-to-one association)
 Use Transitive Persistence (Many-to-one association)
 Use Automatic Dirty Checking
 Transaction commit and rollback behavior
Things to be tried at leisure
 Entity mode
 Nested transactions
 Different id generation mechanisms
 Session.flush(), refresh()
 Composite id
 2 session factories
 Replication across session factories
 2 Tables per class
Data Model

 Emp
 Designation

designation emp
Setup
 Create a new workspace
 Open Eclipse
 Create a java project called “Training”
 Create a folder called resources
 Create packages “objectmodel”, “sessionfactory” and “dao”
 Right click on Training and click on add Hibernate capabilities
 Create objectmodel, sessionfactory to local objectmodel,
sessionfactory respectively
 Copy BaseHibernateDAO, IBaseHibernateDAO to local dao
 Create a new class TrainingDAO which extends BaseHibernateDAO
 Write a method in which you fetch a designation object with id = 1
Tasks
- Fetch a department with id = 1
- Create and save a new Employee
- Fetch same employee without designation
- and print employee's name and then try to
- print designation.name
- Fetch employee with designation, print
- employee name and then try to print designation
- name
- Create a new designation, set it into the
- fetched employee object and call update()
- Fetch that employee w/o departments
- Fetch an employee with departments

All work described was performed by Capgemini or a Capgemini affiliate


5
Hibernate – OR Mapping
-Gopal Patel

CONFIDENTIAL
Sample Configuration
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN“
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping package=“com.example">
<class name=“User“ table=“USER“ discriminator-value=“U">
<id name="id">
<generator class="native"/>
</id>

<property name=“name“ type=“string“ not-null="true“ update="false"/>


<property name=“email“ type="eg.types.EmailType“ not-null="true“ update="false"/>

<many-to-one name=“group“ column=“group_id“ update="false"/>

<set name=“orders“ inverse="true“ order-by=“order_id">


<key column=“id"/>
<one-to-many class=“User"/>
</set>
</class>
</hibernate-mapping>

CONFIDENTIAL
7
Hibernate-mapping

<hibernate-mapping
default-cascade="cascade_style"
default-lazy="true|false"
auto-import="true|false"
package="package.name"
/>
Class element
<class
name="ClassName”
table="tableName"
mutable=“true|false”
dynamic-update="true|false"
dynamic-insert="true|false"
select-before-update="true|false"
where="arbitrary sql where condition"
batch-size="N"
optimistic-lock="none|version|dirty|all"
lazy="true|false"
entity-name="EntityName"
rowid="rowid"
subselect="SQL expression"
abstract="true|false"
discriminator-value="discriminator_value"
/>

CONFIDENTIAL
9
Examples

<class name="Summary">
<subselect>
select item.name, max(bid.amount), count(*)
from item
join bid on bid.item_id = item.id
group by item.name
</subselect>
<synchronize table="item"/>
<synchronize table="bid"/>
<id name="name"/>
..
</class>
CONFIDENTIAL
10
Id element

<id
name="propertyName"
type="typename"
column="column_name"
unsaved-value="null|any|none|undefined|id_value"
access="field|property|ClassName">

<generator class="generatorClass"/>
</id>

CONFIDENTIAL
11
ID
increment
»
Generators
 generates identifiers of type long, short or int that are unique only when no other process is
inserting data into the same table. Do not use in a cluster.
»Identity
 supports identity columns in DB2, MySQL, MS SQL Server, Sybase and HypersonicSQL.
The returned dentifier is of type long, short or int.
»sequence
 uses a sequence in DB2, PostgreSQL, Oracle, SAP DB, McKoi or a generator in Interbase.
The returned identifier is of type long, short or int
»hilo
 uses a hi/lo algorithm to efficiently generate identifiers of type long, short or int, given a table
and column (by default hibernate_unique_key and next_hi respectively) as a source of hi
values. The hi/lo algorithm generates identifiers that are unique only for a particular
database.
»seqhilo
 uses a hi/lo algorithm to efficiently generate identifiers of type long, short or int, given a
named database sequence.
»uuid
 uses a 128-bit UUID algorithm to generate identifiers of type string, unique within a network
(the IP address is used). The UUID is encoded as a string of hexadecimal digits of length 32.

CONFIDENTIAL
12
»guid
ID Generators
 uses a database-generated GUID string on MS SQL Server and MySQL.

»native
 picks identity, sequence or hilo depending upon the capabilities of the underlying database.

»assigned
 lets the application to assign an identifier to the object before save() is called. This is the default strategy if
no <generator> element is specified.

»select
 retrieves a primary key assigned by a database trigger by selecting the row by some unique key and
retrieving the primary key value.

»foreign
 uses the identifier of another associated object. Usually used in conjunction with a <one-to-one> primary key
association.

»sequence-identity
 a specialized sequence generation strategy which utilizes a database sequence for the actual value
generation, but combines this with JDBC3 getGeneratedKeys to actually return the generated identifier
value as part of the insert statement execution. This strategy is only known to be supported on Oracle 10g
drivers targetted for JDK 1.4. Note comments on these insert statements are disabled due to a bug in the
Oracle drivers.

CONFIDENTIAL
13
property
<property
name="propertyName"
column="column_name"
type="typename"
update="true|false"
insert="true|false"
formula="arbitrary SQL expression"
access="field|property|ClassName"
lazy="true|false"
unique="true|false"
not-null="true|false"
optimistic-lock="true|false"
generated="never|insert|always"
length="L"
precision="P"
/>

CONFIDENTIAL
14
Using derived properties
»The value of a derived property is calculated at runtime by evaluation of an
expression.
»You define the expression using the formula attribute.
»The SQL formula is evaluated every time the entity is retrieved from the database.
»Formulas may refer to columns of the database table, call SQL functions, and include
SQL subselects.

<property name="totalIncludingTax"
formula="TOTAL + TAX_RATE * TOTAL"
type="big_decimal"/>
<property
name="averageBidAmount"
formula="( select AVG(b.AMOUNT) from BID b
where b.ITEM_ID = ITEM_ID )"
type="big_decimal"/>

CONFIDENTIAL
15
Properties

<properties
name="logicalName" (1)
insert="true|false" (2)
update="true|false" (3)
optimistic-lock="true|false" (4)
unique="true|false" (5)
>
<property ...../>
<many-to-one .... />
........
</properties>

CONFIDENTIAL
16
Properties example

<class name="Person">
<id name="personNumber"/>
...
<properties name="name"
unique="true" update="false">
<property name="firstName"/>
<property name="initial"/>
<property name="lastName"/>
</properties>
</class>
CONFIDENTIAL
17
Many-to-one
<many-to-one
name="propertyName"
column="column_name"
class="ClassName"
cascade="cascade_style"
fetch="join|select"
update="true|false"
insert="true|false"
property-ref="propertyNameFromAssociatedClass"
access="field|property|ClassName"
unique="true|false"
not-null="true|false"
optimistic-lock="true|false"
lazy="proxy|no-proxy|false"
not-found="ignore|exception"
entity-name="EntityName"
formula="arbitrary SQL expression"
/>

CONFIDENTIAL
18
Unidirectional Association
<class name=“emp">
<id name="id" column=“emp_id">
<generator class="native"/>
</id>
<many-to-one name="address"
column="addressId"
not-null="true"/>
</class>

<class name="Address">
<id name="id" column="addressId">
<generator class="native"/>
</id>
</class>
Bidirectional association
<class name=“user">
<id name="id" column=“user_id">
<generator class="native"/>
</id>
<many-to-one name=“order“ column=" order_id“ not-null="true"/>
</class>
<class name=“Order">
<id name="id" column=“order_id">
<generator class="native"/>
</id>
<set name=“user" inverse="true">
<key column=“order_id"/>
<one-to-many class=“User"/>
</set>
</class>
One-to-one
<one-to-one
name="propertyName"
class="ClassName"
cascade="cascade_style"
fetch="join|select"
property-ref="propertyNameFromAssociatedClass"
access="field|property|ClassName"
formula="any SQL expression"
lazy="proxy|no-proxy|false"
entity-name="EntityName"
constrained="true|false"
/>

CONFIDENTIAL
21
Unidirectional

<class name=“emp">
<id name="id" column=“emp_id">
<generator class="native"/>
</id>
<many-to-one name="address“ column="addressId"
unique="true“ not-null="true"/>
</class>
<class name="Address">
<id name="id" column="addressId">
<generator class="native"/>
</id>
</class>
Bidirectional – same
primary key
<class name="Person">
<id name="id" column="personId">
<generator class="native"/>
</id>
<one-to-one name="address"/>
</class>
<class name="Address">
<id name="id" column="personId">
<generator class="foreign">
<param name="property">person</param>
</generator>
</id>
<one-to-one name="person“ constrained="true"/>
</class>
Bidirectional – foreign keys

<class name="Person">
<id name="id" column="personId">
<generator class="native"/>
</id>
<many-to-one name="address“ column="addressId"
unique="true“ not-null="true"/>
</class>
<class name="Address">
<id name="id" column="addressId">
<generator class="native"/>
</id>
<one-to-one name="person“ property-ref="address"/>
</class>
join

<join
table="tablename"
fetch="join|select"
inverse="true|false"
optional="true|false">
<key ... />
<property ... />
...
</join>

CONFIDENTIAL
25
Join example

<class name = “Person”>


<join table="PersonAddress“ optional="true">
<key column="personId" unique="true"/>
<many-to-one name="address"
column="addressId“ not-null="true"/>
</join>
</class>
<class name=“Address”>
</class>

CONFIDENTIAL
26
Mapping collections

CONFIDENTIAL
Scenario
Everyuser places some orders.
ORDER table contains USER_ID as foreign
key.
Hence there is parent-child relationship
between USER and ORDER.

CONFIDENTIAL
28
Collections in POJO
public class User implements Serializable {

public User() {}

private Long id;

private Set orders = new HashSet();

public String getOrders() {


return orders;
}
public void setOrders(Set orders) {
this.orders = orders;
}
}

CONFIDENTIAL
29
Collection mapping
<class name=“User">
<id name=“id" column=“USER_ID"/>
<set name=“orders“ table=“ORDER” lazy=“true”>
<key column=“USER_ID" not-null="true"/>
<one-to-many class=“Order"/>
</set>
</class>

CONFIDENTIAL
30
Types of collection mappings
 <map>
 <list>
 <array>
 <primitive-array>
 <set>
 <bag>

CONFIDENTIAL
31
Scenario

CONFIDENTIAL
32
Bag
 Bag
 An unordered collection that permits duplicate elements is called a
bag.
 List in java can be used to map a bag but order wont be preserved

<bag name="images" lazy="true" table="ITEM_IMAGE">


<collection-id type="long" column="ITEM_IMAGE_ID">
<generator class="sequence"/>
</collection-id>
<key column="ITEM_ID"/>
<element type="string" column="FILENAME" not-null="true"/>
</bag>

CONFIDENTIAL
33
Scenario

CONFIDENTIAL
34
List
 A <list> mapping requires the addition of an index column to the
database table.
 The index column defines the position of the element in the
collection.
<list name="images" lazy="true" table="ITEM_IMAGE">
<key column="ITEM_ID"/>
<index column="POSITION"/>
<element type="string" column="FILENAME" not-null="true"/>
</list>

CONFIDENTIAL
35
Scenario

CONFIDENTIAL
36
Map
 Duplicate elements are allowed
<map name="images" lazy="true" table="ITEM_IMAGE">
<key column="ITEM_ID"/>
<index column="IMAGE_NAME" type="string"/>
<element type="string" column="FILENAME" not-null="true"/>
</map>

CONFIDENTIAL
37
Sorted collections
 Sort attribute
 Set and map can be sorted using sort but bag
and lists cant
 Sort can accept a comparator class as value

 order-by attribute
 Set and Bag can be sorted using order-by but
lists cant.

CONFIDENTIAL
38
Examples of Sorted
collections
<map name="images“ lazy="true“
table="ITEM_IMAGE“ sort="natural">
<key column="ITEM_ID"/>
<index column="IMAGE_NAME" type="string"/>
<element type="string" column="FILENAME" not-null="true"/>
</map>

<map name="images“ lazy="true” table="ITEM_IMAGE"


sort="auction.util.comparator.ReverseStringComparator">
<key column="ITEM_ID"/>
<index column="IMAGE_NAME" type="string"/>
<element type="string" column="FILENAME" not-null="true"/>
</map>
CONFIDENTIAL
39
Example
<map name="images“ lazy="true"
table="ITEM_IMAGE“ order-
by="IMAGE_NAME asc">
<key column="ITEM_ID"/>
<index column="IMAGE_NAME" type="string"/>
<element type="string" column="FILENAME" not-
null="true"/>
</map>

CONFIDENTIAL
40
Attributes
<map
name="propertyName"
table="table_name"
schema="schema_name"
lazy="true|extra|false"
inverse="true|false"
cascade="all|none|save-update|delete|all-delete-orphan|delet(6)e-orphan”
sort="unsorted|natural|comparatorClass"
order-by="column_name asc|desc"
where="arbitrary sql where condition"
fetch="join|select|subselect"
batch-size="N"
access="field|property|ClassName"
optimistic-lock="true|false"
>
<key .... /> //Collection key column, foreign key
<map-key .... />
<element .... />
</map> CONFIDENTIAL
41
HQL

CONFIDENTIAL
42
HQL

 HQL is generally used for object retrieval


 In Hibernate 3, HQL supports insert, delete and update in bulk
mode
 Object names used in the HQL are case-sensitive
 Returns objects rather than resultsets
 Supports features like pagination, inner/outer joins, projections,
aggregation, ordering & sub-queries
 Supports most of the SQL functions
 Supports order by and group by
First Trip to HQL World
 from emp e
 from emp e where e.emp_no like ‘e_%’
 From emp e where e.email is not null
 Select d from department where d.department_id = 1
 From emp e
left outer join e.addresses as addresses
 From emp e
right outer join e.addresses as addresses
 Select e.name from emp e
 Select e.designation.name from emp e
Fetch

 From emp e
left outer join fetch e.addresses address
left outer join fetch e.designation
left outer join fetch address.timezone
 Associations/Collections get initialized. It overrides the lazy
declarations

 From emp e fetch all properties


 Fetches all the properties
Aggregate functions

 Avg, sum, max, count, min etc..


 Select avg(d.count), sum(d.count),
max(d.count), min(d.count) from designation
d
Expressions Examples

 From Department d where d.id between 1 and 3


 From department d where d.id in {1,3}
 From designation de where de.count > 0
 From emp e where maxindex(e.addresses) > 2
 From emp e where maxelement(e.addresses) > 2
 From emp e where upper(e.name) like ’E_%’

 SQL functions like any, some, all, exists, in are supported


 Indexed collections may be referred to by index
Sub-queries

 Select e from emp e where e.designation.id


in (select d.id from designation d)
Executing HQL

 Session.createQuery(“HQL query…”).list();
 Session.createQuery(“from emp e where e.emp_no like
?”).setString(0,”e_%”).list();
 Session.createQuery(“from emp e where e.emp_no = :name
”).setString(“name”,”e_%”).list();

 Session.createQuery(“select e from emp e where name =


‘XYZ’”).uniqueResult();

 Session.createQuery().iterate();
 Session.createQuery(“select e.name, e.email from emp e”).list();
Executing Queries

List names = new ArrayList();


names.add(“xyz");
names.add(“abc");
Query q = sess.createQuery("from emp e
where e.name in (:namesList)");
q.setParameterList("namesList", names);
List cats = q.list();
Named Queries

 Queries are externalized to a xml file


<query name="ByName"><![CDATA[
from objectmodel.designation as de
where de.name = ?
] ]></query>
 Parameter binding and execution is done
programmatically
Query q = sess.getNamedQuery(“ByName");
q.setString(0, name);
List cats = q.list();

You might also like