136
Hibernate 3.5 Prepared By Mumbai Academics https ://www.facebook.com/mumbai.academics.gro up

Hibernate tutorial

Embed Size (px)

DESCRIPTION

Hibernate tutorial for beginners - Learn Hibernate 3.x starting from environment setup, Object Relational Mapping (ORM), Query Language, Native SQL, Caching, Interceptors, Persistent Classes, Persistent Objects, Collections, Associations and components, and Hibernate tools.

Citation preview

Page 1: Hibernate tutorial

Hibernate 3.5Prepared By Mumbai Academics

https://www.facebook.com/mumbai.academics.group

Page 2: Hibernate tutorial

Hibernate 3.5Lesson 01: Introduction to ORM and its Need

Page 3: Hibernate tutorial

3

Lesson Objectives

• In this lesson, you will learn about:– Object/Relation Mapping– Object-relation Impedence Mismatch– Hibernate 3.5 – Building a Simple Application

Page 4: Hibernate tutorial

Demo• Down This Files To Get Demos

hibernate_demos.rar

Page 5: Hibernate tutorial

5

What is Object/Relation Mapping?

• It means how we will map the relational world with the object world. – In the relational world, the data is in the form of a

table that contains rows and column.– In the object world, the data is in the form of an

object.

Page 6: Hibernate tutorial

An ORM Solution

• It consists of:– An API, to perform CRUD (Create, Read, Update,

Delete) operations on objects of persistent classes– A language to specify queries that refer to classes

and properties of classes– A facility, to specify mapping metadata– A technique, for the ORM implementation to

interact with transactional objects to perform dirty checking. Lazy association, fetching, and other optimization functions.

Page 7: Hibernate tutorial

Why ORM?

• It “shields” developers from “messy” SQL• This view holds that object oriented developers

cannot be expected to understand SQL or relational databases

• Some of the benefits of ORM and Hibernate are:– Productivity– Maintainability– Performance– Vendor independence

Page 8: Hibernate tutorial

Persistence and Relational Database

• Persistence means that we would like our application's data to outlive the applications process.

• In Java terms, we would like the state of (some of) our objects to live beyond the scope of the JVM so that the same state is available later.

• Hibernate is concerned with data persistence as it applies to relational databases (RDBMS). In the world of object-oriented applications, there is often a discussion about using an object database (ODBMS) as opposed to a RDBMS.

Page 9: Hibernate tutorial

9

Object-Relation Impedence Mismatch

• Object-relational Impedence Mismatch' means that object models and relational models do not work very well together. RDBMSs represent data in a tabular format, whereas object-oriented languages, such as Java, represent it as an interconnected graph of objects. Loading and storing graphs of objects using a tabular relational database exposes us to mismatch problems...– Granularity – Inheritance (subtypes) – Identity

Page 10: Hibernate tutorial

10

Granularity

• Sometimes you will have an object model, which has more classes than the number of corresponding tables in the database (The object model is more granular than the relational model) and vice versa.

Page 11: Hibernate tutorial

11

Subtypes (inheritance)

• Inheritance is a natural paradigm in object-oriented programming languages. However, RDBMSs do not define anything similar on the whole.

Page 12: Hibernate tutorial

12

Identity

• An RDBMS defines exactly one notion of 'sameness': the primary key. Java, however, defines both object identity (a==b) and object equality (a.equals(b)).

Page 13: Hibernate tutorial

13

Introduction to Hibernate 3.5

• Hibernate is an open source ORM implementation• It mediates the application’s interaction with a

relational database, leaving the developer free to concentrate on the business problem at hand.

• Hibernate is an non-intrusive solution.

Page 14: Hibernate tutorial

14

Introduction to Hibernate 3.5

• Hibernate 3.5 is an implementation of the Java Persistence API standard that replaced older Java persistence solutions such as the entity beans from Enterprise Java Beans 2.

• Hibernate 3.5 has introduced standard persistence mechanism JPA and Infispan as caching mechanism.

Page 15: Hibernate tutorial

Hibernate Features

• No build time bytecode generation• No special database tables• Flexible O/R mapping

Page 16: Hibernate tutorial

Hibernate Features (continued)

• Uses get/set methods and empty parameter constructor

• Supports fine-grained objects• Lazy initialization• Automatic primary key generation with

multiple strategies

Page 17: Hibernate tutorial

Hibernate Features (continued)

• Support for transactions including optimistic locking • Built in connection pooling or use popular connection

pools• Built in caching (Hibernate Dual Layer Cache Architecture)• Abstracts the variations in dialects between databases.

For example:– <property

name="dialect">org.hibernate.dialect.HSQLDialect</property>• Query by criteria

– For a complete set of features see http://www.hibernate.org

Page 18: Hibernate tutorial

18

Why Hibernate?

• Impedance mismatch– Object-oriented vs. relational

• Java developers are not database developers– Reduce the need for developers to know and fully

understand database design, SQL, performance tuning– Increase portability across database vendors

• Increase performance by deferring to experts– Potential decrease in database calls– More efficient SQL statements– Hibernate cache usage

Page 19: Hibernate tutorial

Disadvantages of Hibernate

• Hibernate may be slower than JDBC• Hibernate’s connection pool is not great, but it

works with the other popular connection pools

• Support for HQL (Hibernate Query Language) syntax cannot be found outside of Hibernate

Page 20: Hibernate tutorial

Hibernate Components

Page 21: Hibernate tutorial

Overview of Hibernate API in a layered Architecture

Page 22: Hibernate tutorial

Architecture Classes

• SessionFactory (org.hibernate.SessionFactory)– A threadsafe (immutable) cache of compiled mappings for a single

database. – A factory for Session and a client of ConnectionProvider.

• Session (org.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.

Page 23: Hibernate tutorial

Architecture Classes

• 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 and detached objects and collections– Instances 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 24: Hibernate tutorial

Configuration

• Three modes of configuration– Using properties file– Programmatic– Declarative using XML configuration file

Page 25: Hibernate tutorial

XML Configuration File <?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.driver_class">org.hsqldb.jdbcDriver</property>………..<mapping resource="events/Event.hbm.xml"/><mapping resource="events/Person.hbm.xml"/></session-factory></hibernate-configuration>

Page 26: Hibernate tutorial

Use Configuration to get SessionFactory

• 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:

– SessionFactory sessions = cfg.buildSessionFactory();

Page 27: Hibernate tutorial

JDBC Connections

• Usually, you want to have the SessionFactory to create and pool JDBC connections for you. If you take this approach, opening a Session is as simple as:

• Session session = sessions.openSession(); – // open a new Session

• As soon as you do something that requires access to the database, a JDBC connection will be obtained from the pool

Page 28: Hibernate tutorial

JDBC Connections

• Hibernate will obtain (and pool) connections using java.sql.DriverManager, if you set the following properties:

Page 29: Hibernate tutorial

JDBC Connections

• For use inside an application server, you should almost always configure Hibernate to obtain connections from an application server Datasource registered in JNDI. You'll need to set at least one of the following properties:

Page 30: Hibernate tutorial

Use XML Configuration to Get sessionFactory

• Obtain SessionFactory as – SessionFactory sf = new

Configuration().configure().buildSessionFactory(); • You can pick a different XML configuration file

using – SessionFactory sf = new

Configuration() .configure("catdb.cfg.xml") .buildSessionFactory();

Page 31: Hibernate tutorial

31

Building a Hibernate Application

• Define the domain model• Setup your Hibernate configuration

– hibernate.cfg.xml• Create the domain object mapping files

– <domain_object>.hbm.xml• Make Hibernate aware of the mapping files

– Update the hibernate.cfg.xml with list of mapping files

Page 32: Hibernate tutorial

32

Review – Questions

• Implement a HibernateUtil class.– Usually taken from the Hibernate documentation

• Write your code

Page 33: Hibernate tutorial

Account Object/Table

Page 34: Hibernate tutorial

hibernate.cfg.xml

Page 35: Hibernate tutorial

hibernate.cfg.xml

Page 36: Hibernate tutorial

hibernate.cfg.xml

Page 37: Hibernate tutorial

Configuring Hibernate

• There are multiple ways to configure Hibernate and an application can leverage multiple methodsat once

• Hibernate will look for and use configuration• properties in the following order

– hibernate.properties (when ‘new Configuration()’ is called)

– hibernate.cfg.xml (when ‘configure()’ is called on Configuration)

– Programatic configuration settings

Page 38: Hibernate tutorial

Object Mapping Files

Page 39: Hibernate tutorial

Account.hbm.xml Mapping File

Page 40: Hibernate tutorial

Hibernate ID Generators

• Native: Leverages underlying database method for generating ID(sequence, identity, etc…)

• Increment: Automatically reads max value of identity column and increments by 1

• UUID: Universally unique identifier combining IP & Date (128-bit) Many more…

Page 41: Hibernate tutorial

Some more ID generetaors

Page 42: Hibernate tutorial

Identify Mapping Files in the hibernate.cfg.xml

Page 43: Hibernate tutorial

HibernateUtil

• Convenience class to handle building and obtaining the Hibernate Session Factory.– Use recommended by the Hibernate org

• Session Factory is thread-safe– Singleton for the entire application

• Used to build Hibernate ‘Sessions’– Hibernate Sessions are NOT thread safe– One per thread of execution

Page 44: Hibernate tutorial

HibernateUtil

Page 45: Hibernate tutorial

Testing the Code

Page 46: Hibernate tutorial

Demo

• StartingHibernate Demo

Page 47: Hibernate tutorial

Hibernate 3.5

Lesson 2: The Persistence Life Cycle

Page 48: Hibernate tutorial

48

Lesson Objectives

• After completing this lesson, you will be able to explain the following topics:– Hibernate Object Life Cycle – Persistent State – Transient Object – Removed State– Detached State

Page 49: Hibernate tutorial

Hibernate Object Life Cycle

Page 50: Hibernate tutorial

50

Transient State

• All objects start off in the transient state– Account account = new Account();

• account is a transient object

• Hibernate is not aware of the object instance• Not related to database row

– No value for accountId• Garbage collected when no longer referenced

by any other objects

Page 51: Hibernate tutorial

Persistent State

• Hibernate is aware of, and managing, the object• It has a database ID• This is the only state where objects are saved to the

database• Objects are made persistent through calls against the

Hibernate session• – session.save(account); – session.lock(account);• – session.update(account); – session.merge(account);

Page 52: Hibernate tutorial

Persistent State (Contd…)

Page 53: Hibernate tutorial

Removed State

• A previously persistent object that is deleted from the database.– session.delete(account);

• Java instance may still exist, but it is ignored by Hibernate– Any changes made to the object are not saved to the

database– Picked up for garbage collection once it falls out of

scope• Hibernate does not null-out the in-memory object

Page 54: Hibernate tutorial

54

Removed State (Contd…)

Page 55: Hibernate tutorial

55

Detached State

• A persistent object that is still referenced after closure of the active session.– session.close() changes object’s state from

persisted to detached• Still represents a valid row in the database• No longer managed by Hibernate.

– Changes made to detached objects are not saved to the database while object remains in the detached state

Page 56: Hibernate tutorial

56

Detached State (Contd…)

Page 57: Hibernate tutorial

57

Persistence Context

• Managed object environment– No API or concrete object to reference, just

conceptual– Thought of as containing:

• Graph of managed persistent instances• List of SQL statements to send to the database

• Each Hibernate session is said to have one ‘persistence context’.

Page 58: Hibernate tutorial

58

Persistence Context (Contd…)

Page 59: Hibernate tutorial

Flushing the Context

• The process of synchronizing the memory state with the database, usually only at the end of a unit of work, is called flushing Submits the stored SQL statements to the database

• Occurs when:– Transactions commit() or rollback() is called– session.flush() is called explicitly– Before a query is executed

• If stored statements would affect the results of the query

Page 60: Hibernate tutorial

Flushing Modes

• Flush modes– session.setFlushMode()

• FlushMode.AUTO: Default. Called as described above• FlushMode.COMMIT: Not flushed before queries• FlushMode.MANUAL: Only when explicit flush() is

called

Page 61: Hibernate tutorial

CRUD (Create, Read, Update, Delete)

• Creating a row in database through hibernate using

• save() method

Page 62: Hibernate tutorial

CRUD (Contd…)

• Reading data from the database using hibernate

Page 63: Hibernate tutorial

CRUD - Reading Data

• Updating the data

Page 64: Hibernate tutorial

CRUD - Updating the Record in Database

• Any persistent object returned by get() or any other kind of query is already associated with the current Session and transaction context.

• It can be modified, and its state will be synchronized with the database.

Page 65: Hibernate tutorial

CRUD - Difference Between load() & get()

Page 66: Hibernate tutorial

CRUD - Updating detached Instance

Page 67: Hibernate tutorial

CRUD - Updating detached Instance (Contd…)

• The lock() method also allows an application to reassociate

• an object with a new session. However, the detached instance

• has to be unmodified! //just reassociate:sess.lock(fritz, LockMode.NONE);//do a version check, then reassociate:sess.lock(izi, LockMode.READ);//do a version check, using SELECT ... FOR UPDATE, then reassociate:sess.lock(pk, LockMode.UPGRADE);

Page 68: Hibernate tutorial

CRUD - Delete

• In order to allow convenient removal of entities from the database, the Session interface provides a delete() method, as follows:

public void delete(Object object) throws HibernateException

Page 69: Hibernate tutorial

CRUD – Delete (Contd…)

• Session session = sessions.openSession();• Transaction tx = session.beginTransaction();• session.delete(user); tx.commit();

session.close();

• In this case, the call to delete() undertakes two actions: It associates the object with the session and then schedules the object for deletion, executed on tx.commit().

Page 70: Hibernate tutorial

Refreshing Entities

• Hibernate provides a mechanism to refresh persistent objects from their database representation.

• Use one of the refresh() methods on the Session interface to refresh an instance of a persistent object, as follows:

public void refresh(Object object) throws HibernateException

public void refresh(Object object, LockMode lockMode) throws HibernateException

Page 71: Hibernate tutorial

DemoDemo: HibernateCRUD

Page 72: Hibernate tutorial

Transactions

• A transaction is a unit of work guaranteed to behave as if you have exclusive use of the database. If you wrap your work in a transaction, the behavior of other system users will not affect your data. A transaction can be started, committed to write data to the database, or rolled back to remove all changes from the beginning onward .

• Transactions and locking are intimately related—the locking techniques chosen to enforce a transaction can determine both the performance and likelihood of success of the transaction.

Page 73: Hibernate tutorial

Transactions (Contd…)

• To achieve this, you obtain a Transaction object from the database (beginning the transaction) and manipulate the session as shown in the following code:

Page 74: Hibernate tutorial

Hibernate 3.5Lesson 3: Hibernate Association and Collection Mapping

Page 75: Hibernate tutorial

75

Lesson Objectives• After completing this lesson, you will be able

to explain the following topics:• Unidirectional Associations

– many-to-one– one-to-one

• Bi-directional Associations– one-to-many/many-to-one– one-to-one

Page 76: Hibernate tutorial

Lesson Objectives (Contd…)• Collection Mapping

– Association Using SET

Page 77: Hibernate tutorial

Associations

• Association represents relationship between entities.

• There is no directionality involved in relational world, its just a matter of writing a query.

• But there is notion of directionality which is possible in java.

• For hibernate association are of two types:– Unidirectional– Bidirectional

Page 78: Hibernate tutorial

Unidirectional Associations (many-to-one)

• <class name="Person"> <id name="id" column="personId"><generator class="native"/> </id><many-to-one name="address" class=“Address” column="addressId" not-null="true"/ cascade=“all”></class> <class name="Address"> <id name="id" column="addressId"> <generator class="native"/> </id></class>

Page 79: Hibernate tutorial

One-To-One<class name="Person"> <id name="id" column="personId"><generator class="native"/></id> </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>

Page 80: Hibernate tutorial

Using many-to-one Element to Create one-to-one Relationship

Page 81: Hibernate tutorial

Student.hbm.xml <class name="com.patni.student.Student" table="STUDENT"><id name="studentId" type="long" column="STUDENT_ID"><generator class="native" /></id><property name="studentName" type="string" not-null="true"length="100" column="STUDENT_NAME" />

<many-to-one name="studentAddress"class="com.patni.student.Address“

column="STUDENT_ADDRESS"not-null="true" cascade="all" unique="true" /></class>

Page 82: Hibernate tutorial

Address.hbm.xml <class name="com.patni.student.Address" table="ADDRESS"><id name="addressId" type="long" column="ADDRESS_ID"><generator class="native" /></id><property name="street" column="ADDRESS_STREET" type="string"length="250" /><property name="city" column="ADDRESS_CITY" type="string"length="50" /><property name="state" column="ADDRESS_STATE" type="string"length="50" /><property name="zipcode" column="ADDRESS_ZIPCODE" type="string"length="10" /></class

Page 83: Hibernate tutorial

Student class

public class Student implements java.io.Serializable {private long studentId;private String studentName;private Address studentAddress; public Student() {}...

Page 84: Hibernate tutorial

Address class

public class Address implements java.io.Serializable {private long addressId;private String street;private String city;private String state;private String zipcode; public Address() {}

Page 85: Hibernate tutorial

Demo

• One_to_one • One_to_many

Page 86: Hibernate tutorial

Bidirectional Associationsone-to-many / many-to-one

<class name="Person"><id name="id" column="personId"> <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><set name="people" inverse="true"> <key column="addressId"/> <one-to-many class="Person"/> </set> </class>

Page 87: Hibernate tutorial

Bidirectional Associations(fk) one-to-one

A bidirectional one-to-one association on a foreign key is common: <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>

Page 88: Hibernate tutorial

Bidirectional Associations(pk) one-to-one

A bidirectional one-to-one association on a primary key uses the special id generator: <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>

Page 89: Hibernate tutorial

Collection Mapping

• Association & Collection mapping tags are practically identical.

• Hibernate Collection Types– <set>

• Unordered/Ordered, requiring value column

– <map>• Unordered/Ordered, requiring key and value columns

Page 90: Hibernate tutorial

Collection Mapping (Contd…)

– <list>• Ordered, requiring an index column on the referenced

object table

– <array>• Map to Java Type and Primitive Arrays• Ordered, requiring an index column on the referenced

object table

– <bag>• No direct implementation available in Java• Unordered/ordered collection allowing duplicates

Page 91: Hibernate tutorial

Collection Mapping (Contd…)

• Realized through Collection/List• Requires value column

– <idbag>• Used for many-to-many relationships• Same as Bag, but with additional identifier column used

for surrogate keys• Requires an ID Generator just like Entity classes

Page 92: Hibernate tutorial

Association as <set>• Maps to a ‘Set’ interface

– Impls include HashSet, TreeSet, etc…• Can be optionally sorted

– EBiller has many EBills (1:M / M:1)• EBill Mapping

<many-to-one name="ebiller" column="EBILLER_ID"class="courses.hibernate.vo.EBiller" />

• EBiller Mapping<set name="ebills" inverse="true"

sort="unsorted|natural|my.custom.MyComparator"><key column="EBILLER_ID" not-null="true"/><one-to-many class="courses.hibernate.vo.EBill"/></set>

Page 93: Hibernate tutorial

Demo

• One_to_one • One_to_many • hibernateOneToManybidirectional • OneToManyBiDirectionalWithSet

Page 94: Hibernate tutorial

Hibernate 3.5Lesson 04: Transaction Management

Page 95: Hibernate tutorial

Lesson Objectives

• In this lesson, you will learn:– Programmatic Transaction Management – Declarative Transaction Management – Using Data Source for Transaction Management

Page 96: Hibernate tutorial

Transaction

• Represents a single unit-of-work• All or nothing – either all of the actions get

committed or the entire effort fails.• Example:

– Transfer Money Between Accounts– Step 1: Withdraw $500 from Savings Account– Step 2: Deposit $500 into Checking Account

• What happens if the system crashes after Step 1, but before Step 2?

Page 97: Hibernate tutorial

Transaction (continued)

• Hibernate communicates with the database via a JDBC Connection; hence it must support both APIs. In a stand-alone (or web-based) application, only the JDBC transaction handling is available; in an application server, Hibernate can use JTA.

• Since we would like Hibernate application code to look the same in both managed and non-managed environments, Hibernate provides its own abstraction layer, hiding the underlying transaction API.

Page 98: Hibernate tutorial

Transaction• Hibernate needs a way to abstract the various transaction strategies from the

environment. Hibernate has its own Transaction class that is accessible from the Session interface, demonstrated here:

• In this example, factory is an initialized SessionFactory instance. This code creates an instance of the org.hibernate.Transaction class and then commits the Transaction instance.Notice that you don't need to call session.flush(). Committing a transaction automatically flushes the Session object.

• The Event instance is persisted to the database when the transaction is committed. The transaction strategy you use (JDBC or JTA) doesn't matter to the application code-it's set in the Hibernate configuration file.

Page 99: Hibernate tutorial

Transaction• The transaction.factory_class property defines the transaction strategy that Hibernate uses.

The default setting is to use JDBC transactions since they're the most common. To use JTA transactions, you need to set the following properties in hibernate.cfg.xml:

• The transaction.factory_class property tells Hibernate that you'll be using JTA transactions. Currently, the only other option to JTA is JBDC transactions, which is the default. JTA transactions are retrieved from a JNDI URI, which is specified using the jta.User-Transaction property. If you don't know the URI for your specific application server, the default value is java:comp/UserTransaction.

Page 100: Hibernate tutorial

Programmatic Transactions in Hibernate

• org.hibernate.Transaction– begin();– commit();– rollback();– setTimeout();– Obtained through session

• session.beginTransaction();• session.getTransaction();

– Works in a non-managed plain JDBC environment and also with application servers using JTA

Page 101: Hibernate tutorial

Programmatic Transactions in Hibernate

– javax.transaction.UserTransaction• Java Transaction API (JTA) version• Hibernate recommends this as the primary choice whenever it’s available

Page 102: Hibernate tutorial

Programmatic Transactions in Native Hibernate

try {Session session = HibernateUtil.getSessionFactory().getCurrentSession();// session obtains connection and sets autoCommit(false)session.beginTransaction();// ...// modify and call persistent methods on various objects// ...// flush the Persistence Context and commit to the database session.getTransaction().commit();catch (HibernateException he) {// roll back if an exception occurs session.getTransaction().rollback();}finally {// close session and return connection to pool session.close();}

Page 103: Hibernate tutorial

Programmatic Transactions in Hibernate with JTA

• Hibernate recommends leveraging JTA over native Hibernate APIs when available

• Within a JTA environment, actions are tied to the JTA system transaction

• Need to tell Hibernate about JTA, and the vendor specific TransactionManager

Page 104: Hibernate tutorial

Programmatic Transactions in Hibernate with JTA

Page 105: Hibernate tutorial

Programmatic Transactions in Hibernate with JTA

<session-factory>...<property name="current_session_context_class">jta</property><propertyname="transaction.factory_class">org.hibernate.transaction.JTATransactionFactory</property><property name="transaction.manager_lookup_class"><!-- selected on a per-vendor basis -->org.hibernate.transaction.JBossTransactionManagerLookup</property>...</session-factory>

Page 106: Hibernate tutorial

Declarative Transactions

• Pushes transaction management and responsibility to the app server.– Container-managed-transactions

• Doesn’t require extra boilerplate code– Much cleaner and easier to read– Easier to follow the business logic

• No need to manually start and stop transactions!

Page 107: Hibernate tutorial

Declarative Transactions

<!-- Declarative Transaction Management --><property name="current_session_context_class">jta</property><property name="transaction.factory_class">org.hibernate.transaction.CMTTransactionFactory</property><property name="transaction.manager_lookup_class">org.hibernate.transaction.JBossTransactionManagerLookup

</property>

Page 108: Hibernate tutorial

JBoss Datasource – lecture6DS.xml<?xml version="1.0" encoding="UTF-8"?>

<datasources><local-tx-datasource><jndi-name>Lecture6DS</jndi-name>

<!-- Oracle Configuration --><connection-url>

jdbc:oracle:thin:@localhost:1521:XE</connection-url><driver-class>

oracle.jdbc.driver.OracleDriver</driver-class><user-name>lecture6</user-name> <password>lecture6</password>

<min-pool-size>5</min-pool-size><max-pool-size>100</max-pool-size>

</local-tx-datasource></datasources>

Page 109: Hibernate tutorial

Demo• Herbernate_with_Datasource

Page 110: Hibernate tutorial

Hibernate 3.5Lesson 05: Searches and Queries

Page 111: Hibernate tutorial

111

Lesson Objectives

• In this lesson, you will learn:– Hibernate Query Language(HQL) – Hibernate Projections

Page 112: Hibernate tutorial

Hibernate Query Language(HQL)

• HQL is a language for talking about “sets of objects”

• It unifies relational operations with object models• HQL is an object-oriented query language, similar

to SQL, but instead of operating on tables and columns, HQL works with persistent objects and their properties.

• HQL is a language with its own syntax and grammar.

Page 113: Hibernate tutorial

Hibernate Query Language

• Hibernate Query Language is used to execute queries against database.

• Hibernate automatically generates the sql query and execute it against underlying database if HQL is used in the application.

• HQL is based on the relational object models and makes the SQL object oriented.

• Hibernate Query Language uses Classes and properties instead of tables and columns.

• Hibernate Query Language is extremely powerful and it supports Polymorphism, Associations, Much less verbose than SQL

Page 114: Hibernate tutorial

Hibernate Query Language

• Make SQL be object oriented– Classes and properties instead of tables and columns– Polymorphism– Associations– Much less verbose than SQL

• Full support for relational operations– Inner/outer/full joins, cartesian products– Projection– Aggregation (max, avg) and grouping– Ordering– Subqueries– SQL function calls

Page 115: Hibernate tutorial

Why to use HQL?

• Full support for relational operations • Return result as Object • Polymorphic Queries

– Polymorphic queries results the query results along with all the child objects if any

• Easy to Learn • Support for Advance features

– HQL contains many advance features such as pagination, fetch join with dynamic profiling, Inner/outer/full joins, Cartesian products. It also supports Projection, Aggregation (max, avg) and grouping

• Database independent

Page 116: Hibernate tutorial

The from Clause and Aliases• Simple shortcut query to select all objects from the Product table

“from Product as p or from Product as product”• The from clause is very basic and useful for working directly with

objects.• String SQL_QUERY ="from Insurance insurance";

Query query = session.createQuery(SQL_QUERY); for(Iterator it=query.iterate();it.hasNext();){ Insurance insurance=(Insurance)it.next(); System.out.println("ID: " +insurance.getLngInsuranceId()); System.out.println("First Name: " + insurance.getInsuranceName()); } session.close();

Page 117: Hibernate tutorial

HQL select Clause • The select clause provides more control over the result set than the from clause. If

you want to obtain the properties of objects in the result set, use the select clause

• //Create Select Clause HQL String SQL_QUERY ="Select insurance.lngInsuranceId,

insurance.insuranceName," + "insurance.investementAmount,insurance.investementDate from Insurance insurance";

Query query = session.createQuery(SQL_QUERY); for(Iterator it=query.iterate();it.hasNext();){ Object[] row = (Object[]) it.next(); System.out.println("ID: " + row[0]); System.out.println("Name: " + row[1]); System.out.println("Amount: " + row[2]); }session.close();

Page 118: Hibernate tutorial

HQL select Clause• Where Clause is used to limit the results returned from database. It

can be used with aliases and if the aliases are not present in the Query, the properties can be referred by name.

• String SQL_QUERY =" from Insurance as insurance where insurance.lngInsuranceId='1'"; Query query = session.createQuery(SQL_QUERY); for(Iterator it=query.iterate() ;it.hasNext();)

• { Insurance insurance=(Insurance)it.next(); System.out.println("ID: " + insurance.getLngInsuranceId()); System.out.println("Name: " +insurance.getInsuranceName()); }

Page 119: Hibernate tutorial

The where clause

• The where clause allows you to refine the list of instances returned. If no alias exists, you can refer to properties by name: – from Cat where name='Fritz' – from Cat as cat where cat.name='Fritz'

• This returns instances of Cat named 'Fritz'.

– select foo from Foo foo, Bar bar where foo.startDate = bar.date

• returns all instances of Foo with an instance of bar with a date property equal to the startDate property of the Foo

Page 120: Hibernate tutorial

The order by clause

• The list returned by a query can be ordered by any property of a returned class or components:

• “from DomesticCat cat order by cat.name asc, cat.weight desc, cat.birthdate”

• The optional asc or desc indicate ascending or descending order respectively.

Page 121: Hibernate tutorial

The group by clause

• A query that returns aggregate values can be grouped by any property of a returned class or components: – select cat.color, sum(cat.weight), count(cat) from

Cat cat group by cat.color .• A having clause is also allowed.

– select cat.color, sum(cat.weight), count(cat) from Cat cat group by cat.color having cat.color in (eg.Color.TABBY, eg.Color.BLACK)

Page 122: Hibernate tutorial

HQL aggregate functions

• Hibernate supports multiple aggregate functions. when they are used in HQL queries, they return an aggregate value (such as sum, average, and count) calculated from property values of all objects satisfying other query criteria.

• These functions can be used along with the distinct and all options, to return aggregate values calculated from only distinct values and all values (except null values), respectively.

Page 123: Hibernate tutorial

HQL aggregate functions

• Following is a list of aggregate functions with their respective syntax; all of them are self-explanatory.count( [ distinct | all ] object | object.property ) count(*) (equivalent to count(all ...), counts null values also) sum ( [ distinct | all ] object.property) avg( [ distinct | all ] object.property) max( [ distinct | all ] object.property) min( [ distinct | all ] object.property)

Page 124: Hibernate tutorial

HQL aggregate functions

• Example:“select cat.weight + sum(kitten.weight) from Cat cat join cat.kittens kitten group by cat.id, cat.weight “select distinct cat.name from Cat cat select count(distinct product.supplier.name) from Product product

Page 125: Hibernate tutorial

Using Restrictions with HQL

• As with SQL, you use the where clause to select results that match your query’s expressions. HQL provides many different expressions that you can use to construct a query. In the HQL language grammar, there are the following possible expressions:– Logic operators: OR, AND, NOT– Equality operators: =, <>, !=, ^=– Comparison operators: <, >, <=, >=, like, not like,

between, not between

Page 126: Hibernate tutorial

Using Restrictions with HQL

– Math operators: +, -, *, /– Concatenation operator: ||– Cases: Case when <logical expression> then <unary

expression> else _<unaryexpression> end– Collection expressions: some, exists, all, any

• Example:– from Product where price > 25.0 and name like 'Mou%‘– from DomesticCat cat where cat.name between 'A' and 'B' – from DomesticCat cat where cat.name in ( 'Foo', 'Bar',

'Baz' )

Page 127: Hibernate tutorial

Using Named Parameters

• Hibernate supports named parameters in its HQL queries. This makes writing queries that accept input from the user easy—and you do not have to defend against SQL injection attacks.

• SQL injection is an attack against applications that create SQL directly from user input with string concatenation. For instance, if we accept a name from the user through a web application form, then it would be very bad form to construct an SQL (or HQL) query like this:– String sql = "select p from products where name = '" + name +

"'";

Page 128: Hibernate tutorial

Using Named Parameters

• Hibernate’s named parameters are similar to the JDBC query parameters (?) you may already be familiar with, but Hibernate’s parameters are less confusing. It is also more straightforward to use Hibernate’s named parameters if you have a query that uses the same parameter in multiple places

• The simplest example of named parameters uses regular SQL types for the parameters:

String hql = "from Product where price > :price";Query query = session.createQuery(hql);query.setDouble("price",25.0);List results = query.list();

Page 129: Hibernate tutorial

Using Named Parameters• When the value to be provided will be known only at run time, you

can use some of HQL’s object-oriented features to provide objects as values for named parameters. The Query interface has a setEntity() method that takes the name of a parameter and an object.String supplierHQL = "from Supplier where name='MegaInc'";Query supplierQuery = session.createQuery(supplierHQL);Supplier supplier = (Supplier) supplierQuery.list().get(0);String hql = "from Product as product where product.supplier=:supplier";Query query = session.createQuery(hql);query.setEntity("supplier",supplier);List results = query.list()

Page 130: Hibernate tutorial

Named HQL Query in Mapping File

Page 131: Hibernate tutorial

Get Named HQL Query from Mapping File

• Session session = HibernateUtil.currentSession(); Query query = session.getNamedQuery("HQLpricing"); List results = query.list(); displayObjectList(results);static public void displayObjectList(List list) { Iterator iter = list.iterator(); if (!iter.hasNext()) { System.out.println("No objects to display."); return; } while (iter.hasNext()) { System.out.println("New object"); Object obj = (Object) iter.next(); System.out.println(obj); }}

Page 132: Hibernate tutorial

Obtaining a Unique Result

• HQL’s Query interface provides a uniqueResult() method for obtaining just one object from an HQLquery.

Query query = session.createQuery(hql);query.setMaxResults(1);Product product = (Product) query.uniqueResult();//test for null here if needed

Page 133: Hibernate tutorial

Sorting Results with the order by Clause

• To sort your HQL query’s results, you will need to use the order by clause. You can order the results by any property on the objects in the result set: either ascending (asc) or descending (desc). You can use ordering on more than one property in the query if you need to. A typical HQL query for sorting resultslooks like this:from Product p where p.price>25.0 order by p.price descIf you wanted to sort by more than one property, you would just add the additional properties to the end of the order by clause, separated by commas. For instance, you could sort by product price and the supplier’s name, as follows:from Product p order by p.supplier.name asc, p.price asc

Page 134: Hibernate tutorial

Using Multiple Table • Associations allow you to use more than one class in an HQL query,

just as SQL allows you to use joins between tables in a relational database. Add an association to an HQL query with the join clause.

• Hibernate supports five different types of joins: inner join, cross join, left outer join, right outer join, and full outer join.

• If you use cross join, just specify both classes in the from clause (from Product p, Supplier s).

• For the other joins, use a join clause after the from clause. Specify the type of join, the object property to join on, and an alias for the other class.

Page 135: Hibernate tutorial

Using Multiple Table• Example1:

“select s.name, p.name, p.price from Product p inner join p.supplier as s”

• Example2: “from Cat as cat inner join cat.mate as mate left outer join cat.kittens as kitten “

• You may supply extra join conditions using the HQL with keyword.

• Example 3:“from Cat as cat left join cat.kittens as kitten with kitten.bodyWeight > 10.0 “

Page 136: Hibernate tutorial

Demo• Down This Files To Get Demos

hibernate_demos.rar