SlideShare una empresa de Scribd logo
1 de 136
Hibernate 3.5
Prepared By Mumbai Academics
https://www.facebook.com/mumbai.academics.group
Hibernate 3.5
Lesson 01: Introduction to ORM and its Need
Lesson Objectives
• In this lesson, you will learn about:
– Object/Relation Mapping
– Object-relation Impedence Mismatch
– Hibernate 3.5
– Building a Simple Application

3
Demo
• Down This Files To Get Demos
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.

5
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.
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
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.
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
9
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.

10
Subtypes (inheritance)
• Inheritance is a natural paradigm in objectoriented programming languages.
However, RDBMSs do not define anything
similar on the whole.

11
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)).

12
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.

13
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.
14
Hibernate Features
• No build time bytecode generation
• No special database tables
• Flexible O/R mapping
Hibernate Features (continued)
• Uses get/set methods and empty parameter
constructor
• Supports fine-grained objects
• Lazy initialization
• Automatic primary key generation with
multiple strategies
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
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
18
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
Hibernate Components
Overview of Hibernate API in a layered
Architecture
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.
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.
Configuration
• Three modes of configuration
– Using properties file
– Programmatic
– Declarative using XML configuration file
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>
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();
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
JDBC Connections
• Hibernate will obtain (and pool) connections
using java.sql.DriverManager, if you set the
following properties:
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:
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();
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
31
Review – Questions
• Implement a HibernateUtil class.
– Usually taken from the Hibernate documentation

• Write your code

32
Account Object/Table
hibernate.cfg.xml
hibernate.cfg.xml
hibernate.cfg.xml
Configuring Hibernate
• There are multiple ways to configure Hibernate
and an application can leverage multiple methods
at 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
Object Mapping Files
Account.hbm.xml Mapping File
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…
Some more ID generetaors
Identify Mapping Files in the
hibernate.cfg.xml
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
HibernateUtil
Testing the Code
Demo
• StartingHibernate Demo
Hibernate 3.5
Lesson 2: The Persistence Life Cycle
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

48
Hibernate Object Life Cycle
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
50
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);
Persistent State (Contd…)
•
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
Removed State (Contd…)

54
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
55
Detached State (Contd…)

56
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’.
57
Persistence Context (Contd…)

58
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
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
CRUD (Create, Read, Update, Delete)
• Creating a row in database through hibernate
using
• save() method
CRUD (Contd…)
• Reading data from the database using
hibernate
CRUD - Reading Data
• Updating the data
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.
CRUD - Difference Between load() &
get()
CRUD - Updating detached Instance
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);
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
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().
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
Demo
Demo: HibernateCRUD
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.
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:
Hibernate 3.5
Lesson 3: Hibernate Association and Collection Mapping
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

75
Lesson Objectives (Contd…)

• Collection Mapping

– Association Using SET
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
Unidirectional Associations (many-toone)
• <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>
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>
Using many-to-one Element to Create one-to-one Relationship
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" notnull="true"length="100" column="STUDENT_NAME" />
<many-to-one
name="studentAddress"class="com.patni.student.Address
“
column="STUDENT_ADDRESS"notnull="true" cascade="all" unique="true" />
</class>
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
Student class
public class Student implements java.io.Serializable {
private long studentId;
private String studentName;
private Address studentAddress;
public Student() {
}
.
.
.
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() {
}
Demo
• One_to_one
• One_to_many
Bidirectional Associations
one-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>
Bidirectional Associations(fk) one-toone
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>
Bidirectional Associations(pk) one-toone
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>
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
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
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
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>
Demo
•
•
•
•

One_to_one
One_to_many
hibernateOneToManybidirectional
OneToManyBiDirectionalWithSet
Hibernate 3.5
Lesson 04: Transaction Management
Lesson Objectives
• In this lesson, you will learn:
– Programmatic Transaction Management
– Declarative Transaction Management
– Using Data Source for Transaction Management
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?
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 nonmanaged environments, Hibernate provides its
own abstraction layer, hiding the underlying
transaction API.
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.

•
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.
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
Programmatic Transactions in
Hibernate
– javax.transaction.UserTransaction
• Java Transaction API (JTA) version
• Hibernate recommends this as the primary choice whenever it’s available
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();
}
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
Programmatic Transactions in Hibernate with JTA
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>
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!
Declarative Transactions
<!-- Declarative Transaction Management -->
<property
name="current_session_context_class">jta</property
>
<property name="transaction.factory_class">
org.hibernate.transaction.CMTTransactionFactory</propert
y>
<property name="transaction.manager_lookup_class">
org.hibernate.transaction.JBossTransactionManagerLookup
</property>
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>
Demo

• Herbernate_with_Datasource
Hibernate 3.5
Lesson 05: Searches and Queries
Lesson Objectives
• In this lesson, you will learn:
– Hibernate Query Language(HQL)
– Hibernate Projections

111
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.
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
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
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
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();
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();
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());
}
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
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.
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)
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.
HQL aggregate functions
• Following is a list of aggregate functions with
their respective syntax; all of them are selfexplanatory.
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)
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
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
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' )
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 +
"'";
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();
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()
Named HQL Query in Mapping File
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); }}
Obtaining a Unique Result
• HQL’s Query interface provides a uniqueResult()
method for obtaining just one object from an HQL
query.

Query query = session.createQuery(hql);
query.setMaxResults(1);
Product product = (Product) query.uniqueResult();
//test for null here if needed
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 results
looks like this:
from Product p where p.price>25.0 order by p.price desc
If 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
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.
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 “
Demo
• Down This Files To Get Demos

Más contenido relacionado

La actualidad más candente

La actualidad más candente (20)

Spring & hibernate
Spring & hibernateSpring & hibernate
Spring & hibernate
 
Java persistence api 2.1
Java persistence api 2.1Java persistence api 2.1
Java persistence api 2.1
 
Hibernate ppt
Hibernate pptHibernate ppt
Hibernate ppt
 
JPA For Beginner's
JPA For Beginner'sJPA For Beginner's
JPA For Beginner's
 
Hibernate
HibernateHibernate
Hibernate
 
Jsf
JsfJsf
Jsf
 
Mvc architecture
Mvc architectureMvc architecture
Mvc architecture
 
Microservices with Java, Spring Boot and Spring Cloud
Microservices with Java, Spring Boot and Spring CloudMicroservices with Java, Spring Boot and Spring Cloud
Microservices with Java, Spring Boot and Spring Cloud
 
Spring data jpa
Spring data jpaSpring data jpa
Spring data jpa
 
Hibernate
HibernateHibernate
Hibernate
 
Spring boot Introduction
Spring boot IntroductionSpring boot Introduction
Spring boot Introduction
 
Spring Boot
Spring BootSpring Boot
Spring Boot
 
JPA Best Practices
JPA Best PracticesJPA Best Practices
JPA Best Practices
 
Spring User Guide
Spring User GuideSpring User Guide
Spring User Guide
 
Introduction to Spring Framework
Introduction to Spring FrameworkIntroduction to Spring Framework
Introduction to Spring Framework
 
Spring Boot and REST API
Spring Boot and REST APISpring Boot and REST API
Spring Boot and REST API
 
Spring - Part 1 - IoC, Di and Beans
Spring - Part 1 - IoC, Di and Beans Spring - Part 1 - IoC, Di and Beans
Spring - Part 1 - IoC, Di and Beans
 
JQuery introduction
JQuery introductionJQuery introduction
JQuery introduction
 
Lecture 10 - Java Server Faces (JSF)
Lecture 10 - Java Server Faces (JSF)Lecture 10 - Java Server Faces (JSF)
Lecture 10 - Java Server Faces (JSF)
 
Springboot Microservices
Springboot MicroservicesSpringboot Microservices
Springboot Microservices
 

Destacado

Введение в hibernate
Введение в hibernateВведение в hibernate
Введение в hibernateUnguryan Vitaliy
 
Parallel batch processing with spring batch slideshare
Parallel batch processing with spring batch   slideshareParallel batch processing with spring batch   slideshare
Parallel batch processing with spring batch slideshareMorten Andersen-Gott
 
JPA 2.1 performance tuning tips
JPA 2.1 performance tuning tipsJPA 2.1 performance tuning tips
JPA 2.1 performance tuning tipsosa_ora
 
Ahea Team Spring batch
Ahea Team Spring batchAhea Team Spring batch
Ahea Team Spring batchSunghyun Roh
 
JPA - Java Persistence API
JPA - Java Persistence APIJPA - Java Persistence API
JPA - Java Persistence APIThomas Wöhlke
 
Hibernate
Hibernate Hibernate
Hibernate Sunil OS
 
Overview of JPA (Java Persistence API) v2.0
Overview of JPA (Java Persistence API) v2.0Overview of JPA (Java Persistence API) v2.0
Overview of JPA (Java Persistence API) v2.0Bryan Basham
 
Hibernate Developer Reference
Hibernate Developer ReferenceHibernate Developer Reference
Hibernate Developer ReferenceMuthuselvam RS
 

Destacado (10)

Spring batch
Spring batchSpring batch
Spring batch
 
Введение в hibernate
Введение в hibernateВведение в hibernate
Введение в hibernate
 
Spring Batch Introduction
Spring Batch IntroductionSpring Batch Introduction
Spring Batch Introduction
 
Parallel batch processing with spring batch slideshare
Parallel batch processing with spring batch   slideshareParallel batch processing with spring batch   slideshare
Parallel batch processing with spring batch slideshare
 
JPA 2.1 performance tuning tips
JPA 2.1 performance tuning tipsJPA 2.1 performance tuning tips
JPA 2.1 performance tuning tips
 
Ahea Team Spring batch
Ahea Team Spring batchAhea Team Spring batch
Ahea Team Spring batch
 
JPA - Java Persistence API
JPA - Java Persistence APIJPA - Java Persistence API
JPA - Java Persistence API
 
Hibernate
Hibernate Hibernate
Hibernate
 
Overview of JPA (Java Persistence API) v2.0
Overview of JPA (Java Persistence API) v2.0Overview of JPA (Java Persistence API) v2.0
Overview of JPA (Java Persistence API) v2.0
 
Hibernate Developer Reference
Hibernate Developer ReferenceHibernate Developer Reference
Hibernate Developer Reference
 

Similar a Hibernate 3.5 ORM Introduction

Hibernate in XPages
Hibernate in XPagesHibernate in XPages
Hibernate in XPagesToby Samples
 
Free Hibernate Tutorial | VirtualNuggets
Free Hibernate Tutorial  | VirtualNuggetsFree Hibernate Tutorial  | VirtualNuggets
Free Hibernate Tutorial | VirtualNuggetsVirtual Nuggets
 
Hibernate presentation
Hibernate presentationHibernate presentation
Hibernate presentationManav Prasad
 
Hibernate Session 1
Hibernate Session 1Hibernate Session 1
Hibernate Session 1b_kathir
 
Hibernate interview questions
Hibernate interview questionsHibernate interview questions
Hibernate interview questionsvenkata52
 
Java hibernate orm implementation tool
Java hibernate   orm implementation toolJava hibernate   orm implementation tool
Java hibernate orm implementation tooljavaease
 
2010 05-21, object-relational mapping using hibernate v2
2010 05-21, object-relational mapping using hibernate v22010 05-21, object-relational mapping using hibernate v2
2010 05-21, object-relational mapping using hibernate v2alvaro alcocer sotil
 
Hibernate jj
Hibernate jjHibernate jj
Hibernate jjJoe Jacob
 
Hibernate example1
Hibernate example1Hibernate example1
Hibernate example1myrajendra
 

Similar a Hibernate 3.5 ORM Introduction (20)

Hibernate
HibernateHibernate
Hibernate
 
Hibernate
HibernateHibernate
Hibernate
 
Hibernate 3
Hibernate 3Hibernate 3
Hibernate 3
 
Hibernate in XPages
Hibernate in XPagesHibernate in XPages
Hibernate in XPages
 
Hibernate
HibernateHibernate
Hibernate
 
Hibernate3 q&a
Hibernate3 q&aHibernate3 q&a
Hibernate3 q&a
 
Persistence hibernate
Persistence hibernatePersistence hibernate
Persistence hibernate
 
Hibernate
HibernateHibernate
Hibernate
 
Free Hibernate Tutorial | VirtualNuggets
Free Hibernate Tutorial  | VirtualNuggetsFree Hibernate Tutorial  | VirtualNuggets
Free Hibernate Tutorial | VirtualNuggets
 
Hibernate
HibernateHibernate
Hibernate
 
Hibernate presentation
Hibernate presentationHibernate presentation
Hibernate presentation
 
Hibernate presentation
Hibernate presentationHibernate presentation
Hibernate presentation
 
Hibernate Session 1
Hibernate Session 1Hibernate Session 1
Hibernate Session 1
 
Hibernate interview questions
Hibernate interview questionsHibernate interview questions
Hibernate interview questions
 
Java hibernate orm implementation tool
Java hibernate   orm implementation toolJava hibernate   orm implementation tool
Java hibernate orm implementation tool
 
Introduction to Hibernate
Introduction to HibernateIntroduction to Hibernate
Introduction to Hibernate
 
Hibernate.pdf
Hibernate.pdfHibernate.pdf
Hibernate.pdf
 
2010 05-21, object-relational mapping using hibernate v2
2010 05-21, object-relational mapping using hibernate v22010 05-21, object-relational mapping using hibernate v2
2010 05-21, object-relational mapping using hibernate v2
 
Hibernate jj
Hibernate jjHibernate jj
Hibernate jj
 
Hibernate example1
Hibernate example1Hibernate example1
Hibernate example1
 

Más de Mumbai Academisc (20)

Non ieee java projects list
Non  ieee java projects list Non  ieee java projects list
Non ieee java projects list
 
Non ieee dot net projects list
Non  ieee dot net projects list Non  ieee dot net projects list
Non ieee dot net projects list
 
Ieee java projects list
Ieee java projects list Ieee java projects list
Ieee java projects list
 
Ieee 2014 java projects list
Ieee 2014 java projects list Ieee 2014 java projects list
Ieee 2014 java projects list
 
Ieee 2014 dot net projects list
Ieee 2014 dot net projects list Ieee 2014 dot net projects list
Ieee 2014 dot net projects list
 
Ieee 2013 java projects list
Ieee 2013 java projects list Ieee 2013 java projects list
Ieee 2013 java projects list
 
Ieee 2013 dot net projects list
Ieee 2013 dot net projects listIeee 2013 dot net projects list
Ieee 2013 dot net projects list
 
Ieee 2012 dot net projects list
Ieee 2012 dot net projects listIeee 2012 dot net projects list
Ieee 2012 dot net projects list
 
Spring ppt
Spring pptSpring ppt
Spring ppt
 
Ejb notes
Ejb notesEjb notes
Ejb notes
 
Java web programming
Java web programmingJava web programming
Java web programming
 
Java programming-examples
Java programming-examplesJava programming-examples
Java programming-examples
 
J2ee project lists:-Mumbai Academics
J2ee project lists:-Mumbai AcademicsJ2ee project lists:-Mumbai Academics
J2ee project lists:-Mumbai Academics
 
Web based development
Web based developmentWeb based development
Web based development
 
Jdbc
JdbcJdbc
Jdbc
 
Java tutorial part 4
Java tutorial part 4Java tutorial part 4
Java tutorial part 4
 
Java tutorial part 3
Java tutorial part 3Java tutorial part 3
Java tutorial part 3
 
Java tutorial part 2
Java tutorial part 2Java tutorial part 2
Java tutorial part 2
 
Engineering
EngineeringEngineering
Engineering
 
Jsp
JspJsp
Jsp
 

Último

Culture Uniformity or Diversity IN SOCIOLOGY.pptx
Culture Uniformity or Diversity IN SOCIOLOGY.pptxCulture Uniformity or Diversity IN SOCIOLOGY.pptx
Culture Uniformity or Diversity IN SOCIOLOGY.pptxPoojaSen20
 
ENGLISH6-Q4-W3.pptxqurter our high choom
ENGLISH6-Q4-W3.pptxqurter our high choomENGLISH6-Q4-W3.pptxqurter our high choom
ENGLISH6-Q4-W3.pptxqurter our high choomnelietumpap1
 
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdfLike-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdfMr Bounab Samir
 
How to Add Barcode on PDF Report in Odoo 17
How to Add Barcode on PDF Report in Odoo 17How to Add Barcode on PDF Report in Odoo 17
How to Add Barcode on PDF Report in Odoo 17Celine George
 
AMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdf
AMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdfAMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdf
AMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdfphamnguyenenglishnb
 
Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17
Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17
Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17Celine George
 
Karra SKD Conference Presentation Revised.pptx
Karra SKD Conference Presentation Revised.pptxKarra SKD Conference Presentation Revised.pptx
Karra SKD Conference Presentation Revised.pptxAshokKarra1
 
Barangay Council for the Protection of Children (BCPC) Orientation.pptx
Barangay Council for the Protection of Children (BCPC) Orientation.pptxBarangay Council for the Protection of Children (BCPC) Orientation.pptx
Barangay Council for the Protection of Children (BCPC) Orientation.pptxCarlos105
 
Difference Between Search & Browse Methods in Odoo 17
Difference Between Search & Browse Methods in Odoo 17Difference Between Search & Browse Methods in Odoo 17
Difference Between Search & Browse Methods in Odoo 17Celine George
 
4.18.24 Movement Legacies, Reflection, and Review.pptx
4.18.24 Movement Legacies, Reflection, and Review.pptx4.18.24 Movement Legacies, Reflection, and Review.pptx
4.18.24 Movement Legacies, Reflection, and Review.pptxmary850239
 
AUDIENCE THEORY -CULTIVATION THEORY - GERBNER.pptx
AUDIENCE THEORY -CULTIVATION THEORY -  GERBNER.pptxAUDIENCE THEORY -CULTIVATION THEORY -  GERBNER.pptx
AUDIENCE THEORY -CULTIVATION THEORY - GERBNER.pptxiammrhaywood
 
Procuring digital preservation CAN be quick and painless with our new dynamic...
Procuring digital preservation CAN be quick and painless with our new dynamic...Procuring digital preservation CAN be quick and painless with our new dynamic...
Procuring digital preservation CAN be quick and painless with our new dynamic...Jisc
 
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptx
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptxMULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptx
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptxAnupkumar Sharma
 
ACC 2024 Chronicles. Cardiology. Exam.pdf
ACC 2024 Chronicles. Cardiology. Exam.pdfACC 2024 Chronicles. Cardiology. Exam.pdf
ACC 2024 Chronicles. Cardiology. Exam.pdfSpandanaRallapalli
 
Global Lehigh Strategic Initiatives (without descriptions)
Global Lehigh Strategic Initiatives (without descriptions)Global Lehigh Strategic Initiatives (without descriptions)
Global Lehigh Strategic Initiatives (without descriptions)cama23
 
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATION
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATIONTHEORIES OF ORGANIZATION-PUBLIC ADMINISTRATION
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATIONHumphrey A Beña
 
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptxECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptxiammrhaywood
 
Virtual-Orientation-on-the-Administration-of-NATG12-NATG6-and-ELLNA.pdf
Virtual-Orientation-on-the-Administration-of-NATG12-NATG6-and-ELLNA.pdfVirtual-Orientation-on-the-Administration-of-NATG12-NATG6-and-ELLNA.pdf
Virtual-Orientation-on-the-Administration-of-NATG12-NATG6-and-ELLNA.pdfErwinPantujan2
 

Último (20)

Culture Uniformity or Diversity IN SOCIOLOGY.pptx
Culture Uniformity or Diversity IN SOCIOLOGY.pptxCulture Uniformity or Diversity IN SOCIOLOGY.pptx
Culture Uniformity or Diversity IN SOCIOLOGY.pptx
 
ENGLISH6-Q4-W3.pptxqurter our high choom
ENGLISH6-Q4-W3.pptxqurter our high choomENGLISH6-Q4-W3.pptxqurter our high choom
ENGLISH6-Q4-W3.pptxqurter our high choom
 
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdfLike-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
 
YOUVE_GOT_EMAIL_PRELIMS_EL_DORADO_2024.pptx
YOUVE_GOT_EMAIL_PRELIMS_EL_DORADO_2024.pptxYOUVE_GOT_EMAIL_PRELIMS_EL_DORADO_2024.pptx
YOUVE_GOT_EMAIL_PRELIMS_EL_DORADO_2024.pptx
 
How to Add Barcode on PDF Report in Odoo 17
How to Add Barcode on PDF Report in Odoo 17How to Add Barcode on PDF Report in Odoo 17
How to Add Barcode on PDF Report in Odoo 17
 
AMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdf
AMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdfAMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdf
AMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdf
 
FINALS_OF_LEFT_ON_C'N_EL_DORADO_2024.pptx
FINALS_OF_LEFT_ON_C'N_EL_DORADO_2024.pptxFINALS_OF_LEFT_ON_C'N_EL_DORADO_2024.pptx
FINALS_OF_LEFT_ON_C'N_EL_DORADO_2024.pptx
 
Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17
Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17
Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17
 
Karra SKD Conference Presentation Revised.pptx
Karra SKD Conference Presentation Revised.pptxKarra SKD Conference Presentation Revised.pptx
Karra SKD Conference Presentation Revised.pptx
 
Barangay Council for the Protection of Children (BCPC) Orientation.pptx
Barangay Council for the Protection of Children (BCPC) Orientation.pptxBarangay Council for the Protection of Children (BCPC) Orientation.pptx
Barangay Council for the Protection of Children (BCPC) Orientation.pptx
 
Difference Between Search & Browse Methods in Odoo 17
Difference Between Search & Browse Methods in Odoo 17Difference Between Search & Browse Methods in Odoo 17
Difference Between Search & Browse Methods in Odoo 17
 
4.18.24 Movement Legacies, Reflection, and Review.pptx
4.18.24 Movement Legacies, Reflection, and Review.pptx4.18.24 Movement Legacies, Reflection, and Review.pptx
4.18.24 Movement Legacies, Reflection, and Review.pptx
 
AUDIENCE THEORY -CULTIVATION THEORY - GERBNER.pptx
AUDIENCE THEORY -CULTIVATION THEORY -  GERBNER.pptxAUDIENCE THEORY -CULTIVATION THEORY -  GERBNER.pptx
AUDIENCE THEORY -CULTIVATION THEORY - GERBNER.pptx
 
Procuring digital preservation CAN be quick and painless with our new dynamic...
Procuring digital preservation CAN be quick and painless with our new dynamic...Procuring digital preservation CAN be quick and painless with our new dynamic...
Procuring digital preservation CAN be quick and painless with our new dynamic...
 
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptx
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptxMULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptx
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptx
 
ACC 2024 Chronicles. Cardiology. Exam.pdf
ACC 2024 Chronicles. Cardiology. Exam.pdfACC 2024 Chronicles. Cardiology. Exam.pdf
ACC 2024 Chronicles. Cardiology. Exam.pdf
 
Global Lehigh Strategic Initiatives (without descriptions)
Global Lehigh Strategic Initiatives (without descriptions)Global Lehigh Strategic Initiatives (without descriptions)
Global Lehigh Strategic Initiatives (without descriptions)
 
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATION
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATIONTHEORIES OF ORGANIZATION-PUBLIC ADMINISTRATION
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATION
 
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptxECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
 
Virtual-Orientation-on-the-Administration-of-NATG12-NATG6-and-ELLNA.pdf
Virtual-Orientation-on-the-Administration-of-NATG12-NATG6-and-ELLNA.pdfVirtual-Orientation-on-the-Administration-of-NATG12-NATG6-and-ELLNA.pdf
Virtual-Orientation-on-the-Administration-of-NATG12-NATG6-and-ELLNA.pdf
 

Hibernate 3.5 ORM Introduction

  • 1. Hibernate 3.5 Prepared By Mumbai Academics https://www.facebook.com/mumbai.academics.group
  • 2. Hibernate 3.5 Lesson 01: Introduction to ORM and its Need
  • 3. Lesson Objectives • In this lesson, you will learn about: – Object/Relation Mapping – Object-relation Impedence Mismatch – Hibernate 3.5 – Building a Simple Application 3
  • 4. Demo • Down This Files To Get Demos
  • 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. 5
  • 6. 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.
  • 7. 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
  • 8. 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.
  • 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 9
  • 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. 10
  • 11. Subtypes (inheritance) • Inheritance is a natural paradigm in objectoriented programming languages. However, RDBMSs do not define anything similar on the whole. 11
  • 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)). 12
  • 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. 13
  • 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. 14
  • 15. Hibernate Features • No build time bytecode generation • No special database tables • Flexible O/R mapping
  • 16. Hibernate Features (continued) • Uses get/set methods and empty parameter constructor • Supports fine-grained objects • Lazy initialization • Automatic primary key generation with multiple strategies
  • 17. 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
  • 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 18
  • 19. 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
  • 21. Overview of Hibernate API in a layered Architecture
  • 22. 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.
  • 23. 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.
  • 24. Configuration • Three modes of configuration – Using properties file – Programmatic – Declarative using XML configuration file
  • 25. 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>
  • 26. 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();
  • 27. 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
  • 28. JDBC Connections • Hibernate will obtain (and pool) connections using java.sql.DriverManager, if you set the following properties:
  • 29. 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:
  • 30. 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();
  • 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 31
  • 32. Review – Questions • Implement a HibernateUtil class. – Usually taken from the Hibernate documentation • Write your code 32
  • 37. Configuring Hibernate • There are multiple ways to configure Hibernate and an application can leverage multiple methods at 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
  • 40. 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…
  • 41. Some more ID generetaors
  • 42. Identify Mapping Files in the hibernate.cfg.xml
  • 43. 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
  • 47. Hibernate 3.5 Lesson 2: The Persistence Life Cycle
  • 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 48
  • 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 50
  • 51. 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);
  • 53. 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
  • 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 55
  • 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’. 57
  • 59. 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
  • 60. 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
  • 61. CRUD (Create, Read, Update, Delete) • Creating a row in database through hibernate using • save() method
  • 62. CRUD (Contd…) • Reading data from the database using hibernate
  • 63. CRUD - Reading Data • Updating the data
  • 64. 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.
  • 65. CRUD - Difference Between load() & get()
  • 66. CRUD - Updating detached Instance
  • 67. 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);
  • 68. 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
  • 69. 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().
  • 70. 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
  • 72. 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.
  • 73. 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:
  • 74. Hibernate 3.5 Lesson 3: Hibernate Association and Collection Mapping
  • 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 75
  • 76. Lesson Objectives (Contd…) • Collection Mapping – Association Using SET
  • 77. 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
  • 78. Unidirectional Associations (many-toone) • <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>
  • 79. 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>
  • 80. Using many-to-one Element to Create one-to-one Relationship
  • 81. 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" notnull="true"length="100" column="STUDENT_NAME" /> <many-to-one name="studentAddress"class="com.patni.student.Address “ column="STUDENT_ADDRESS"notnull="true" cascade="all" unique="true" /> </class>
  • 82. 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
  • 83. Student class public class Student implements java.io.Serializable { private long studentId; private String studentName; private Address studentAddress; public Student() { } . . .
  • 84. 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() { }
  • 86. Bidirectional Associations one-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>
  • 87. Bidirectional Associations(fk) one-toone 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>
  • 88. Bidirectional Associations(pk) one-toone 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>
  • 89. 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
  • 90. 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
  • 91. 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
  • 92. 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>
  • 94. Hibernate 3.5 Lesson 04: Transaction Management
  • 95. Lesson Objectives • In this lesson, you will learn: – Programmatic Transaction Management – Declarative Transaction Management – Using Data Source for Transaction Management
  • 96. 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?
  • 97. 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 nonmanaged environments, Hibernate provides its own abstraction layer, hiding the underlying transaction API.
  • 98. 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. •
  • 99. 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.
  • 100. 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
  • 101. Programmatic Transactions in Hibernate – javax.transaction.UserTransaction • Java Transaction API (JTA) version • Hibernate recommends this as the primary choice whenever it’s available
  • 102. 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(); }
  • 103. 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
  • 104. Programmatic Transactions in Hibernate with JTA
  • 105. 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>
  • 106. 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!
  • 107. Declarative Transactions <!-- Declarative Transaction Management --> <property name="current_session_context_class">jta</property > <property name="transaction.factory_class"> org.hibernate.transaction.CMTTransactionFactory</propert y> <property name="transaction.manager_lookup_class"> org.hibernate.transaction.JBossTransactionManagerLookup </property>
  • 108. 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>
  • 110. Hibernate 3.5 Lesson 05: Searches and Queries
  • 111. Lesson Objectives • In this lesson, you will learn: – Hibernate Query Language(HQL) – Hibernate Projections 111
  • 112. 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.
  • 113. 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
  • 114. 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
  • 115. 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
  • 116. 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();
  • 117. 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();
  • 118. 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()); }
  • 119. 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
  • 120. 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.
  • 121. 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)
  • 122. 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.
  • 123. HQL aggregate functions • Following is a list of aggregate functions with their respective syntax; all of them are selfexplanatory. 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)
  • 124. 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
  • 125. 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
  • 126. 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' )
  • 127. 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 + "'";
  • 128. 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();
  • 129. 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()
  • 130. Named HQL Query in Mapping File
  • 131. 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); }}
  • 132. Obtaining a Unique Result • HQL’s Query interface provides a uniqueResult() method for obtaining just one object from an HQL query. Query query = session.createQuery(hql); query.setMaxResults(1); Product product = (Product) query.uniqueResult(); //test for null here if needed
  • 133. 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 results looks like this: from Product p where p.price>25.0 order by p.price desc If 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
  • 134. 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.
  • 135. 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 “
  • 136. Demo • Down This Files To Get Demos