java hibernate

68
HIBERNATE

Upload: ravidownloading

Post on 16-Jan-2016

27 views

Category:

Documents


0 download

DESCRIPTION

Java Hibernate tutorial

TRANSCRIPT

Page 1: Java Hibernate

HIBERNATE

Page 2: Java Hibernate

2

INTRODUCTION

• Working with object-oriented software and a relational database is time consuming

• Need to bridge relational and object-oriented technologies, or to replace one with the other

• However the gap between the two is one of the hard facts

Object-relational mapping tool is required to bridge this gap

Page 3: Java Hibernate

3

What is ORM?

The term “Object-Relational Mapping” (ORM)

refers to the technique of mapping a data representation,

from an object model, to a relational data model with SQL-based schema

Page 4: Java Hibernate

4

Hibernate Overview

• Hibernate is a full-featured, open source Object-Relational mapping framework

• Hibernate is similar to EJB CMP/CMR (container-managed-persistence / container-managed-relationships) and JDO (Java Data Objects)

• Hibernate focuses entirely on OR mapping for relational databases and includes more features than most commercial products

• Hibernate helps in developing persistent classes following object-oriented idiom – including:

association, inheritance, polymorphism, composition, and collections

• Hibernate allows to express queries in its own portable SQL extension (HQL)

• As well as in native SQL, or with an object-oriented Criteria and Example API

• Hibernate is a Professional Open Source project

Page 5: Java Hibernate

5

Hibernate Architecture

Page 6: Java Hibernate

6

Hibernate Architecture Explained

• Persistent Objects:Wherein the tables in the Relational Database are

represented as Java Classes.

• Hibernate.properties:It contains all configuration parameters required for

the application to interact with the database.

• XML Mapping:As the name indicates, links the persistent objects

with the underlying database.

Page 7: Java Hibernate

7

Hibernate Architectural Approaches

• Hibernate is flexible and supports several approaches

• Following are the 2 main Architectural approaches in Hibernate:-– Lite Architecture– Full Cream Architecture

Page 8: Java Hibernate

8

Hibernate “Lite” Architecture

Page 9: Java Hibernate

9

Hibernate “Full Cream” Architecture

Page 10: Java Hibernate

10

Definition of Hibernate Objects• SessionFactory (net.sf.hibernate.SessionFactory)

A threadsafe (immutable) cache of compiled mappings for a single database. A factory for Session and a client of ConnectionProvider. Might hold an optional (second-level) cache of data that is reusable between transactions, at a process- or cluster-level.

• Session (net.sf.hibernate.Session) A single-threaded, short-lived object representing a conversation between

the application and the persistent store. Wraps a JDBC connection. Factory for Transaction. Holds a mandatory (first-level) cache of persistent objects, used when navigating the object graph or looking up objects by identifier.

• Persistent Objects and Collections

Short-lived, single threaded objects containing persistent state and business function. These might be ordinary JavaBeans/POJOs, the only special thing about them is that they are currently associated with (exactly one) Session. As soon as the Session is closed, they will be detached and free to use in any application layer (e.g. directly as data transfer objects to and from presentation).

• Transient Objects and CollectionsInstances of persistent classes that are not currently associated with a

Session. They may have been instantiated by the application and not (yet) persisted or they may have been instantiated by a closed Session.

Page 11: Java Hibernate

11

Definition of Hibernate Objects • Transaction (net.sf.hibernate.Transaction)

(Optional) A single-threaded, short-lived object used by the application to specify atomic units of work. Abstracts application from underlying JDBC, JTA or CORBA transaction. A Session might span several Transactions in some cases.

• ConnectionProvider (net.sf.hibernate.connection.ConnectionProvider)(Optional) A factory for (and pool of) JDBC connections. Abstracts

application from underlying Datasource or DriverManager. Not exposed to application, but can be extended/implemented by the developer.

• TransactionFactory (net.sf.hibernate.TransactionFactory)(Optional) A factory for Transaction instances. Not exposed to the

application, but can be extended/implemented by the developer.

Page 12: Java Hibernate

12

Configuring Hibernate • Two types of Configurations:

– Programmatic Configuration– XML configuration

• Programmatic Configuration– An instance of org.hibernate.cfg.Configuration represents an entire

set of mappings of an application's Java types to an SQL database. – The Configuration is used to build an immutable SessionFactory.

The mappings are compiled from various XML mapping files.

– When all mappings have been parsed by the Configuration, the application must obtain a factory for Session instances.

– This factory is intended to be shared by all application threads.

Page 13: Java Hibernate

13

Programmatic Configuration • Sample “hibernate.properties” file:

hibernate.connection.driver_class = oracle.jdbc.driver.OracleDriver

hibernate.connection.url = jdbc:oracle:thin@localhost:1521:mydatabase

hibernate.connection.username = myuser

hibernate.connection.password = secret

hibernate.dialect = net.sf.hibernate.dialect.Oracle9Dialect

• Programmatically loading of the hibernate.properties:

Configuration cfg = new Configuration();

cfg.getProperties("hibernate.properties");

cfg.addResource("Customer.hbm.xml");

cfg.setProperty(Environment.SHOW_SQL, "true");

SessionFactory sessionFactory = = cfg.buildSessionFactory();

Page 14: Java Hibernate

14

XML Configuration • An alternative approach to configuration - hibernate.cfg.xml. • Used as a replacement for the hibernate.properties file or, if both are present, to

override the properties. • Configuration file is by default expected to be in the root of the CLASSPATH.

<?xml version='1.0' encoding='UTF-8'?>

<!DOCTYPE hibernate-configuration PUBLIC

"-//Hibernate/Hibernate Configuration DTD 3.0//EN"

"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">

<hibernate-configuration>

<session-factory>

<property name="connection.url">jdbc:oracle:thin@localhost:1521:mydatabase</property>

<property name="connection.username">myuser</property>

<property name="connection.driver_class">oracle.jdbc.driver.OracleDriver</property>

<property name="dialect">net.sf.hibernate.dialect.Oracle9Dialect</property>

<property name="connection.password">secret</property>

<property name="hibernate.show_sql">true</property>

<!-- mapping files -->

<mapping resource="Customer.hbm.xml" />

</session-factory>

</hibernate-configuration>

Page 15: Java Hibernate

15

XML Configuration • Loading of the XML configuration

Configuration cfg = new Configuration();

cfg.configure("hibernate.cfg.xml");

SessionFactory sessionFactory = = cfg.buildSessionFactory();

Page 16: Java Hibernate

16

Creating Persistent Classes • Persistent classes are classes in an application that

implement the entities of the business problem. • Not all instances of a persistent class are considered

to be in the persistent state, an instance may instead be transient or detached.

• Hibernate works best if the persistent classes follow some simple rules, also known as the Plain Old Java Object (POJO) programming model.

• All persistent classes must have a default constructor (which may be non-public) so Hibernate can

instantiate them using Constructor.newInstance(). • So, most POJOs are Hibernate-compatible without

any changes.

Page 17: Java Hibernate

17

Hibernate Basic O/R Mapping Elements Hibernate Mapping is an xml file which provides the

complete mapping from the persistence class to the table it represents.

The elements in xml:-

3. <hibernate-mapping>

4. <class>

5. <id>

6. <property>

Page 18: Java Hibernate

18

Hibernate O/R Mapping Root Element Hibernate Mapping is the root element enclosing the

other elements.

A few attributes include:-

<hibernate-mapping

schema="schemaName"

catalog="catalogName"

auto-import="true|false"

package="package.name"

/>

Page 19: Java Hibernate

19

Basic O/R Mapping <class> Element The <class> element is used to map the class name to

the table name. The element with the attributes are as follows:-

<class

name="ClassName"

table="tableName"

discriminator-value="discriminator_value"

schema="owner"

catalog="catalog"

/>

Page 20: Java Hibernate

20

Basic O/R Mapping <id> Elements This tag is used to map the primary key of the table to

an instance variable of the class.

<id

name="propertyName"

type="typename"

column="column_name"

<generator class="generatorClass"/>

</id>

Page 21: Java Hibernate

21

Basic O/R Mapping - <generator> element

The optional <generator> element names a java class used to generate unique identifiers (or primary keys) for instances of the persistent class. Few built-in generators include:-

• increment : generates unique identifiers when no other process is inserting data in the same table.

• sequence : uses the named sequence to generate the unique primary key.

• hilo : A table and column is specified in this case. The column specifies the next unique value for the key.

• seqhilo : A table, column and sequence name is specified. The next unique value is generated using the sequence on the specific column value.

Page 22: Java Hibernate

22

Basic O/R Mapping <property> element • This tag is used to map the other attributes of the

table with the instance variables of the class.

<property

name="propertyName"

column="column_name"

type="typename"

formula="arbitrary SQL expression"

/>• Formula attribute is an SQL expression that defines

the value for a computed property. That is a property which doesn’t have a column of their own.

Page 23: Java Hibernate

23

Hibernate Basic O/R Mapping Hibernate Type :

Hibernate types are used to map the Java property type to a JDBC type. For instance the ‘java.lang.String’ in Java is ‘varchar’ in JDBC. The hibernate type for this is ‘string’.

Mapping type Java type Standard SQL built-in typeinteger 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(1)

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) ('Y' or 'N')

true_false boolean or java.lang.Boolean CHAR(1) ('T' or 'F')

Page 24: Java Hibernate

24

Hibernate Basic O/R Mapping <?xml version="1.0"?>

<!DOCTYPE hibernate-mapping PUBLIC

"-//Hibernate/Hibernate Mapping DTD 2.0//EN"

"http://hibernate.sourceforge.net/hibernate-mapping-2.0.dtd">

<hibernate-mapping>

<class name="com.sample.entity.Customer" table="Customer">

<id name="customerId" column="customer_id" type="long">

<generator class="assigned"/>

</id>

<property name="name" not-null="true"/>

<property name="birthdate" type="date"/>

</class>

</hibernate-mapping>

Page 25: Java Hibernate

25

Hibernate Basic O/R Mapping Elements If the composite keys of a table has to be mapped, the

<composite-id> tag can be used.

Format:-

<composite-id>

<key-property name=“propertyName” type=“type” column=“columnName”/>

<key-property name=“propertyName” type=“type” column=“columnName”/>

</composite-id>

The <key-property> tag specifies the set of columns which makes the composite key.

Page 26: Java Hibernate

26

Retrieving/Storing Java Object • Retrieving Data:

Session session = sessionFactory.getSession();

Customer customerObj = (Customer) session.load(Customer.class, new Long(id));

or

Customer customerObj = (Customer) session.get(Customer.class, new Long(id));

• Storing Data:Customer customerObj = new Customer();

customerObj.setCustomerId(id);

customerObj.setBirthDate(date);

customerObj.setName(“Shiv”);

Session session = sessionFactory.getSession();

Transaction transaction = session.beginTansaction();

session.save(customerObj);

transaction.commit();

Page 27: Java Hibernate

27

Hibernate Collection Mapping

A collection represents a group of objects, known as its elements. Collections in classes can also be mapped using hibernate and this is done using Collection mapping. The elements used are based on the interface used in the class. Like:-

• Set• List• Map

There can be a collection of values or entities– For values, <element> tag is used

– For entities, <one-to-many> or <many-to-many> tag Is used

Page 28: Java Hibernate

28

Hibernate Collection Mapping - Set

• A Set can be thought of as any collection of distinct objects considered as a whole.

Consider the two tables – lecturer and Student

Lect_subjLect_id

Lecturer

Stud_name Lect_idStud_id

Student

Page 29: Java Hibernate

29

Hibernate Collection Mapping - Set Consider the case where 1 lecturer has many students:-

The following set tag is written in the hibernate mapping file of the Lecturer tag.<set name=”setStudents”>

<key column=”Lect_id”>

<one-to-many column=”Lect_id” class=“Student”>

</set>

The <Key> tag here represents the column in the Lecturer class which is a foreign key for the Student class. i.e. the key with which the two classes are linked.

The <one-to-many> tag specifies the class with which the mapping is to be done and the foreign key column in the class.

Page 30: Java Hibernate

30

Hibernate Collection Mapping - Map

Car_Name

Car_id

A map is a simple name-value pair. They have a unique id. <class name="Car" table="Car">

... <map name="Property"> <key column="car_id"/> <index column="Prop_name" type="string"/> <element column="Prop_value" type="string"/> </map>

</class>

Prop_valueProp_nameCar_id

Car Car_prop

Page 31: Java Hibernate

31

Hibernate Collection Mapping - List

List is an ordered collection of entities. Consider the above tables.<class name=“Team” table=“Team”>

<list name="members">

<key column=“team_id" />

<index column="idx" />

<one-to-many class="member" />

</list>

</class>

namemembersteam_id

Member

Parent_idIdxInfoMember_Id

Team

Page 32: Java Hibernate

32

Hibernate Association Mapping • one-to-one association<hibernate-mapping>

<class name="eg.Parent">

<id name="id">

<generator class="sequence"/>

</id>

<one-to-one column=“parent_id”

class="eg.Child"/>

</class>

<class name="eg.Child">

<id name="id">

<generator class="sequence"/>

</id>

<property name="name"/>

</class>

</hibernate-mapping>

• SQL Scripts

create table parent ( id bigint not null primary key )

create table child ( id bigint not null primary key, name varchar(255), parent_id bigint )

alter table child add constraint childfk0 (parent_id) references parent

If the scenario is: one parent-one child

Page 33: Java Hibernate

33

Hibernate Association Mapping • one-to-many association<hibernate-mapping>

<class name="eg.Parent">

<id name="id">

<generator class="sequence"/>

</id>

<set name="children" lazy="true">

<key column="parent_id"/>

<one-to-many class="eg.Child"/>

</set>

</class>

<class name="eg.Child">

<id name="id">

<generator class="sequence"/>

</id>

<property name="name"/>

</class>

</hibernate-mapping>

• SQL Scripts

create table parent ( id bigint not null primary key )

create table child ( id bigint not null primary key, name varchar(255), parent_id bigint )

alter table child add constraint childfk0 (parent_id) references parent

Page 34: Java Hibernate

34

Hibernate Association Mapping • many-to-one association

<hibernate-mapping>

<class name="eg.Parent">

<id name="id">

<generator class="sequence"/>

</id>

<set name="children" lazy="true">

<key column="parent_id"/>

<one-to-many class="eg.Child"/>

</set>

</class>

<class name="eg.Child">

<id name="id">

<generator class="sequence"/>

</id>

<property name="name"/>

<many-to-one name="parent" class="eg.Parent" column="parent_id" not-null="true"/>

</class>

</hibernate-mapping>

• SQL Scripts

create table parent ( id bigint not null primary key )

create table child ( id bigint not null primary key, name varchar(255), parent_id bigint not null)

alter table child add constraint childfk0 (parent_id) references parent

Page 35: Java Hibernate

35

Hibernate Association Mapping • many-to-many association

<hibernate-mapping>

<class name="eg.Parent">

<id name="id">

<generator class="sequence"/>

</id>

<set name="children" lazy="true“ table=“childset”>

<key column="parent_id"/>

<many-to-many class="eg.Child“ column=“child_id”/>

</set>

</class>

<class name="eg.Child">

<id name="id">

<generator class="sequence"/>

</id>

<property name="name"/>

</class>

</hibernate-mapping>

• SQL Scripts

create table parent ( id bigint not null primary key )

create table child ( id bigint not null primary key, name varchar(255) )

create table childset ( parent_id bigint not null, child_id bigint not null, primary key ( parent_id, child_id ) )

alter table childset add constraint childsetfk0 (parent_id) references parent

alter table childset add constraint childsetfk1

(child_id) references child

Page 36: Java Hibernate

36

Hibernate Association Mapping • Saving/Retrieving Data:

Parent parentObj = new Parent();

Child childObj = new Child();

....

Set children = new HashSet();

children.add(childObj);

parentObj.setChildren(children);

session.save(parentObj);

children = parentObj.getChildren();

Page 37: Java Hibernate

37

Hibernate Component MappingMapping a dependant object using Component Mapping:

<class name="eg.Person" table="person">

<id name="Key" column="pid" type="string">

<generator class="uuid.hex"/>

</id>

<property name="birthday" type="date"/>

<component name="Name" class="eg.Name"> <!-- class attribute optional -->

<property name="initial"/>

<property name="first"/>

<property name="last"/>

</component>

</class>

Note: The person table would have the columns pid, birthday,

initial, first and last.

Page 38: Java Hibernate

38

Hibernate Component MappingMapping a collection of dependant objects using Component Mapping:

<set name="someNames" table="some_names" lazy="true"> <key column="id"/> <composite-element class="eg.Name"> <!-- class attribute required --> <property name="initial"/> <property name="first"/> <property name="last"/> </composite-element></set>

Page 39: Java Hibernate

39

Hibernate Component Mapping• Components as Map Indices

– The <composite-index> element lets you map a component class as the key of a Map

• Components as Composite Identifiers<class name="eg.Foo" table"FOOS"> <composite-id name="compId" class="eg.FooCompositeID"> <key-property name="string"/> <key-property name="short"/> <key-property name="date" column="date_" type="date"/> </composite-id> <property name="name"/> ....</class>

Page 40: Java Hibernate

40

Hibernate Inheritance Mapping Inheritance is the process that allows a class to

acquire the properties of another class.

This can be mapped in hibernate using Inheritance mapping.

There are three basic inheritance mapping strategies:-

• Table per class hierarchy• Table per subclass• Table per concrete class

Page 41: Java Hibernate

41

Hibernate Inheritance MappingTable per Class hierarchy:

Table per class strategy maps the whole class hierarchy into one table, and classes are differentiated by a discriminator column.

<class name="Payment" table="PAYMENT"><id name="id" type="long" column="PAYMENT_ID">

<generator class="increment"/></id><discriminator column="PAYMENT_TYPE" type="string"/><property name="amount" column="AMOUNT"/>...<subclass name="CreditCardPayment" discriminator-value="CREDIT">

<property name="creditCardType" column="CCTYPE"/>...

</subclass><subclass name="CashPayment" discriminator-value="CASH">

...</subclass><subclass name="ChequePayment" discriminator-value="CHEQUE">

...</subclass>

</class>

Page 42: Java Hibernate

42

Hibernate Inheritance Mapping• The Table per class strategy uses a <discriminator> element which

specifies the column based on which the subclasses are differentiated.

• The element used to identify each subclass is:- <subclass>

• This element has an attribute discriminator-value, which specifies the value of the discriminator column for this subclass.

• The <property> tags within each <subclass> specifies the properties which are of the subclass.

• For instance, consider the above example. The subclass “CredtCardPayment” has a discriminator-value as “CREDIT” which signifies that the rows in the table “PAYMENT” having the PAYMENT_TYPE value as “CREDIT” belongs to this subclass.

• The property “creditCardType” specifies the attribute of the CreditCardPayment subclass.

Page 43: Java Hibernate

43

Hibernate Inheritance MappingTable per subclass:

Table per subclass strategy maps the base class into one table, and additional attributes in subclasses are mapped to additional tables joined back to the base table with foreign keys.

<class name="Payment" table="PAYMENT"><id name="id" type="long" column="PAYMENT_ID">

<generator class=" increment "/></id><property name="amount" column="AMOUNT"/>...<joined-subclass name="CreditCardPayment" table="CREDIT_PAYMENT">

<key column="PAYMENT_ID"/><property name="creditCardType" column="CCTYPE"/>...

</joined-subclass><joined-subclass name="CashPayment" table="CASH_PAYMENT">

<key column="PAYMENT_ID"/>...

</joined-subclass><joined-subclass name="ChequePayment" table="CHEQUE_PAYMENT">

<key column="PAYMENT_ID"/>...

</joined-subclass></class>

Page 44: Java Hibernate

44

Hibernate Inheritance Mapping• In this strategy, all the attributes of the parent class are present in 1

table and the attributes specific to the subclasses are present in individual tables.

• The mapping is done by using <joined-subclass> element. The subclasses are joined by a foreign key.

• The table attribute of the element signifies the table to which these subclasses are mapped. And the key tag specifies the foreign key of the subclass.

• For instance, in the above example, the attributes specific to the CreditCardPayment subclass is mapped to the CREDIT_PAYMENT table. The PAYMENT_ID column is the foreign key which joins the subclasses to the parent class. The <property> tag specifies the attributes of the respective tables.

Page 45: Java Hibernate

45

Hibernate Inheritance MappingTable per concrete class: In this strategy, each concrete class gets its own table, and all the inherited

attributes are mapped to that table as well. The primary keys have to be shared between the tables.

<class name="Payment"><id name="id" type="long" column="PAYMENT_ID">

<generator class="sequence"/></id><property name="amount" column="AMOUNT"/>...<union-subclass name="CreditCardPayment" table="CREDIT_PAYMENT">

<property name="creditCardType" column="CCTYPE"/>...

</union-subclass><union-subclass name="CashPayment" table="CASH_PAYMENT">

...</union-subclass><union-subclass name="ChequePayment" table="CHEQUE_PAYMENT">

...</union-subclass>

</class>

Page 46: Java Hibernate

46

Hibernate Inheritance Mapping• In this strategy, all the concrete classes have a table of its own.

• The mapping is done by using <union-subclass> element. All the subclasses have a common primary key.

• The table attribute of the element signifies the table to which these subclasses are mapped.

• For instance, in the above example, the attributes specific to the CreditCardPayment subclass is mapped to the CREDIT_PAYMENT table. The PAYMENT_ID column is the primary key of all the subclasses. The <property> tag specifies the attributes of the respective tables.

Page 47: Java Hibernate

47

Hibernate Query Language• Hibernate is equipped with a powerful query language of

its own (HQL) to access Database. • HQL is used for building queries to find or filter data from

DB.• HQL is object oriented version of SQL.• HQL supports transparent and relational persistence.• HQL queries are database independent.• HQL supports advanced features like pagination, fetch

joining with dynamic profiling, inner, outer and full joining.• HQL also supports usage of aggregate functions,

ordering, grouping, sub queries and SQL function calls• Most keywords in SQL are optional in HQL• HQL is case sensitive.

Page 48: Java Hibernate

48

Hibernate Query LanguageSimplest Possible HQL query :-

“from Employee”

Returns all Employee rows from data base in the form of Employee class objects which is mapped to the table Employee

HQL is polymorphic which returns instances of all sub classes of a class

Clauses :-• Select (Optional)• from (Required except with Session and Filter)• where ( Optional)• Other : Order By, Group By, Having…

Page 49: Java Hibernate

49

Writing Simple HQL Before writing the query we have to obtain an instance of

hibernate session which is already opened at the start of the application while loading the configuration files.

“org.hibernate.Session” defines the Session interface to hold the current session.

Session session = HibernateSessionFactory.currentSession();

Now the session variable has an instance of the current session

Page 50: Java Hibernate

50

Writing Simple HQL – where clause

Interface “org.hibernate.Query” defines Query interface to hold the query written on the session

Query query = session.createQuery(“from Employee”); List queryList = query.list(); Now the queryList contains list of objects returned by the query.

where clause allows to narrow the list of instances returned. For example:

“from Employee where Employee.id = :empId”

returns All Employee with id as “empId”.

Page 51: Java Hibernate

51

Writing Simple HQL – select clause

select clause picks the objects and properties to return in the query result set.

“select id from Employee”

This query will return the id of all Employee

“select id from Employee where Employee.salary :> 10000”

This query returns the id of all Employee with salary greater than 10000

Page 52: Java Hibernate

52

Writing Simple HQL – Polymorphic queries

HQL queries are polymorphic due to inheritance mapping.

“from Employee”

Will return the instances not only of Employee but also all the subclasses of Employee.

HQL polymorphic queries will return instances of all the persistence classes that extend the class or implement the interface.

Page 53: Java Hibernate

53

HQL Complex Queries• HQL supports sub queries and co related sub queries if underlying

data base supports it.

• HQL supports all joining queries along with fetch joining.

• HQL allows handling of data with visibility rules using Hibernate Filters.

• Narrowing of Result Objects returned can be done by using Criteria Queries.

• Native SQL queries can be used to write queries in SQL format, retaining the benefits of transparent persistence.

• Named HQL queries can be created for reusability.

Page 54: Java Hibernate

54

Criteria Queries• HQL has criteria queries to perform operations like narrowing the

result set object which are returned based on the criteria defined at runtime.

• Interface “org.hibernate.Criteria” represents query against a particular class.

• Session is a factory for Criteria instances.

Criteria crit = session.createCriteria(Employee.class);crit.setMaxResults(50); List cats = crit.list();

Required criteria can be given to the Criteria instance (crit)

Page 55: Java Hibernate

55

Criteria Queries – Narrowing the result set

List cats = sess.createCriteria(Cat.class) .add( Expression.like("name", "Fritz%") ) .add( Expression.between("weight", minWeight,

maxWeight) ) .list();

List cats = sess.createCriteria(Cat.class) .add( Expression.like("name", "Fritz%") )

.add( Expression.or( Expression.eq( "age", new Integer(0) ), Expression.isNull("age") ) )

.list();

Page 56: Java Hibernate

56

Example QueriesExample example = Example.create(cat) .excludeZeroes() //exclude zero valued properties .excludeProperty("color") //exclude the property named "color" .ignoreCase() //perform case insensitive string comparisons .enableLike(); //use like for string comparisons

List results = session.createCriteria(Cat.class) .add(example) .list();

Page 57: Java Hibernate

57

Native SQLHibernate allows developers to write complex queries in the SQL format

itself using native SQL interface, retaining the advantages of persistence.

Query sqlQuery = sess.createSQLQuery("select {cat.*} from cats {cat}", "cat", Cat.class);

sqlQuery.setMaxResults(50);List cats = sqlQuery.list();

List queryList = session.createSQLQuery(“select * from Employee”).addEntity(Employee.class).list();

addEntity() will do the necessary mapping of Employee table to Employee class which results in returning generic objects.

Page 58: Java Hibernate

58

Native SQL String sql = "select cat.originalId as {cat.id}, "

+ " cat.mateid as {cat.mate}, cat.sex as {cat.sex}, “

+ " cat.weight*10 as {cat.weight}, cat.name as {cat.name}"

+ " from cat_log cat where {cat.mate} = :catId"

List loggedCats = sess.createSQLQuery(sql, "cat", Cat.class) .

setLong("catId", catId) .list();

Page 59: Java Hibernate

59

Named SQL QueryNamed SQL queries can be defined in the mapping document and can

be called in the application by query name which allows reusing of queries

List people = sess.getNamedQuery("mySqlQuery") .setMaxResults(50) .list();

The named SQL query is in the mapping file

<sql-query name = “persons”> <return class = Employee.class/>

Select person from Employee</sql-query>

Page 60: Java Hibernate

60

Hibernate Filters• Hibernate filter is a global named parameterized filter that

may be enabled or disabled for a particular hibernate session.

• In order to use filters they must be defined and attached to appropriate mapping elements. To define a filter use <filter-def> element within <hibernate-mapping/> element.

• Filters can be enabled or disabled at session level.

Page 61: Java Hibernate

61

Hibernate Filters – Narrowing the result setDefining Filter :

<filter-def name = “myFilter”> <filter- param name =“myFilterParam” type =“string”/> </filter-def>

Attaching the filter to a class: <class name =“myClass”…> <filter name = “myFilter” condition = “:myFilterParam = My_Filtered_Column”/> </class>

Enabling or Disabling Filters:

By default Filters are disabled. They have to be enabled on session level to use.

session.enableFilter(“myFilter”)

Will enable the filter “myFilter” for the Session “session”.

Page 62: Java Hibernate

62

Hibernate Session Management / Thread-safe Session objectimport org.hibernate.*;

import org.hibernate.cfg.*;

public class HibernateUtil {

private static final SessionFactory sessionFactory;

static { try { // Create the SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory(); } catch (Throwable ex) { // Make sure you log the exception, as it might be swallowed System.err.println("Initial SessionFactory creation failed." + ex); throw new ExceptionInInitializerError(ex); } }

public static final ThreadLocal session = new ThreadLocal();

public static Session currentSession() throws HibernateException { Session s = (Session) session.get(); // Open a new Session, if this Thread has none yet if (s == null) { s = sessionFactory.openSession(); session.set(s); } return s; }

public static void closeSession() throws HibernateException { Session s = (Session) session.get(); session.set(null); if (s != null) s.close(); }}

Page 63: Java Hibernate

63

Object States

Page 64: Java Hibernate

64

Transactions and Concurrency• You should observe the following practices when

creating Hibernate Sessions:– Never create more than one concurrent Session or

Transaction instance per database connection.– Be extremely careful when creating more than one

Session per database per transaction. The Session itself keeps track of updates made to loaded objects, so a different Session might see stale data.

– The Session is not threadsafe! Never access the same Session in two concurrent threads. A Session is usually only a single unit-of-work!

Page 65: Java Hibernate

65

Transactions and Concurrency• Long session with automatic versioning

– A single Session instance and its persistent instances are used for the whole application transaction.

• Many sessions with automatic versioning– Each interaction with the persistent store occurs in a

new Session.• Application version checking

– Each interaction with the database occurs in a new Session that reloads all persistent instances from the database before manipulating them.

– This approach forces the application to carry out its own version checking to ensure application transaction isolation.

Page 66: Java Hibernate

66

Hibernate Performance Tuning

• Lists, maps and sets are the most efficient collections to update

• One shot delete• Using Proxy for Lazy Loading

• Using batch fetching

• Cache Mapping

Page 67: Java Hibernate

67

References

• Websites:– http://www.hibernate.org– http://hibernate.bluemars.net/hib_docs/referen

ce/en/html/index.html

• Books:– Hibernate Reference Document Version: 3.0.5– Hibernate in Action - By Christian Bauer and

Galvin King

Page 68: Java Hibernate

HappyO/R Mapping with

Hibernate!