Hibernate Query Language
Hibernate Query Language
This manual uses lowercase HQL keywords. Some users find queries with uppercase keywords
more readable, but we find this convention ugly when embedded in Java code.
Prev Next
13.4. DML-style operations Home 14.2. The from clause
from eg.Cat
which simply returns all instances of the class eg.Cat. We don't usually need to qualify the class
name, since auto-import is the default. So we almost always just write:
from Cat
Most of the time, you will need to assign an alias, since you will want to refer to the Cat in other
parts of the query.
It is considered good practice to name query aliases using an initial lowercase, consistent with
Java naming standards for local variables (eg. domesticCat).
Prev Up Next
Chapter 14. HQL: The Hibernate 14.3. Associations and joins
Home
Query Language
• inner join
• left outer join
• right outer join
• full join (not usually useful)
The inner join, left outer join and right outer join constructs may be abbreviated.
from Cat as cat
join cat.mate as mate
left join cat.kittens as kitten
You may supply extra join conditions using the HQL with keyword.
In addition, a "fetch" join allows associations or collections of values to be initialized along with
their parent objects, using a single select. This is particularly useful in the case of a collection. It
effectively overrides the outer join and lazy declarations of the mapping file for associations and
collections. See Section 19.1, “Fetching strategies” for more information.
A fetch join does not usually need to assign an alias, because the associated objects should not be
used in the where clause (or any other clause). Also, the associated objects are not returned
directly in the query results. Instead, they may be accessed via the parent object. The only reason
we might need an alias is if we are recursively join fetching a further collection:
Note that the fetch construct may not be used in queries called using iterate() (though
scroll() can be used). Nor should fetch be used together with setMaxResults() or
setFirstResult() as these operations are based on the result rows, which usually contain
duplicates for eager collection fetching, hence, the number of rows is not what you'd expect. Nor
may fetch be used together with an ad hoc with condition. It is possible to create a cartesian
product by join fetching more than one collection in a query, so take care in this case. Join
fetching multiple collection roles also sometimes gives unexpected results for bag mappings, so
be careful about how you formulate your queries in this case. Finally, note that full join
fetch and right join fetch are not meaningful.
If you are using property-level lazy fetching (with bytecode instrumentation), it is possible to
force Hibernate to fetch the lazy properties immediately (in the first query) using fetch all
properties.
from Document fetch all properties order by name
from Document doc fetch all properties where lower(doc.name)
like '%cats%'
Prev Up Next
14.2. The from clause Home 14.4. Forms of join syntax
The queries shown in the previous section all use the explicit form where the join keyword is
explicitly used in the from clause. This is the recommended form.
The implicit form does not use the join keyword. Instead, the associations are "dereferenced"
using dot-notation. implicit joins can appear in any of the HQL clauses. implicit join result
in inner joins in the resulting SQL statement.
Prev Up Next
14.3. Associations and joins Home 14.5. Refering to identifier property
• The special property (lowercase) id may be used to reference the identifier property of an entity
provided that entity does not define a non-identifier property named id.
• If the entity defines a named identifier property, you may use that property name.
References to composite identifier properties follow the same naming rules. If the entity has a
non-identifier property named id, the composite identifier property can only be referenced by its
defined named; otherwise, the special id property can be used to rerference the identifier
property.
Note: this has changed significantly starting in version 3.2.2. In previous versions, id always
referred to the identifier property no matter what its actual name. A ramification of that decision
was that non-identifier properties named id could never be referenced in Hibernate queries.
Prev Up Next
14.4. Forms of join syntax Home 14.6. The select clause
select mate
from Cat as cat
inner join cat.mate as mate
The query will select mates of other Cats. Actually, you may express this query more compactly
as:
Queries may return properties of any value type including properties of component type:
Queries may return multiple objects and/or properties as an array of type Object[],
This is most useful when used together with select new map:
Prev Up Next
14.5. Refering to identifier property Home 14.7. Aggregate functions
You may use arithmetic operators, concatenation, and recognized SQL functions in the select
clause:
The distinct and all keywords may be used and have the same semantics as in SQL.
Prev Up Next
14.6. The select clause Home 14.8. Polymorphic queries
returns instances not only of Cat, but also of subclasses like DomesticCat. Hibernate queries
may name any Java class or interface in the from clause. The query will return instances of all
persistent classes that extend that class or implement the interface. The following query would
return all persistent objects:
from java.lang.Object o
Note that these last two queries will require more than one SQL SELECT. This means that the
order by clause does not correctly order the whole result set. (It also means you can't call these
queries using Query.scroll().)
Prev Up Next
14.7. Aggregate functions Home 14.9. The where clause
select foo
from Foo foo, Bar bar
where foo.startDate = bar.date
will return all instances of Foo for which there exists an instance of bar with a date property
equal to the startDate property of the Foo. Compound path expressions make the where clause
extremely powerful. Consider:
you would end up with a query that would require four table joins in SQL.
The = operator may be used to compare not only properties, but also instances:
The special property (lowercase) id may be used to reference the unique identifier of an object.
See Section 14.5, “Refering to identifier property” for more information.
Properties of composite identifiers may also be used. Suppose Person has a composite identifier
consisting of country and medicareNumber. Again, see Section 14.5, “Refering to identifier
property” for more information regarding referencing identifier properties.
Likewise, the special property class accesses the discriminator value of an instance in the case
of polymorphic persistence. A Java class name embedded in the where clause will be translated
to its discriminator value.
An "any" type has the special properties id and class, allowing us to express a join in the
following way (where AuditLog.item is a property mapped with <any>).
Notice that log.item.class and payment.class would refer to the values of completely
different database columns in the above query.
Prev Up Next
14.8. Polymorphic queries Home 14.10. Expressions
14.10. Expressions
Prev Chapter 14. HQL: The Hibernate Query Language Next
14.10. Expressions
Expressions allowed in the where clause include most of the kind of things you could write in
SQL:
• mathematical operators +, -, *, /
• binary comparison operators =, >=, <=, <>, !=, like
• logical operations and, or, not
• Parentheses ( ), indicating grouping
• in, not in, between, is null, is not null, is empty, is not empty, member of and not
member of
• "Simple" case, case ... when ... then ... else ... end, and "searched" case, case
when ... then ... else ... end
• string concatenation ...||... or concat(...,...)
• current_date(), current_time(), current_timestamp()
• second(...), minute(...), hour(...), day(...), month(...), year(...),
• Any function or operator defined by EJB-QL 3.0: substring(), trim(), lower(),
upper(), length(), locate(), abs(), sqrt(), bit_length(), mod()
• coalesce() and nullif()
• str() for converting numeric or temporal values to a readable string
• cast(... as ...), where the second argument is the name of a Hibernate type, and
extract(... from ...) if ANSI cast() and extract() is supported by the underlying
database
• the HQL index() function, that applies to aliases of a joined indexed collection
• HQL functions that take collection-valued path expressions: size(), minelement(),
maxelement(), minindex(), maxindex(), along with the special elements() and indices
functions which may be quantified using some, all, exists, any, in.
• Any database-supported SQL scalar function like sign(), trunc(), rtrim(), sin()
• JDBC-style positional parameters ?
• named parameters :name, :start_date, :x1
• SQL literals 'foo', 69, 6.66E+2, '1970-01-01 10:00:01.0'
• Java public static final constants eg.Color.TABBY
from DomesticCat cat where cat.name not between 'A' and 'B'
from DomesticCat cat where cat.name not in ( 'Foo', 'Bar',
'Baz' )
Likewise, is null and is not null may be used to test for null values.
Booleans may be easily used in expressions by declaring HQL query substitutions in Hibernate
configuration:
This will replace the keywords true and false with the literals 1 and 0 in the translated SQL
from this HQL:
You may test the size of a collection with the special property size, or the special size()
function.
For indexed collections, you may refer to the minimum and maximum indices using minindex
and maxindex functions. Similarly, you may refer to the minimum and maximum elements of a
collection of basic type using the minelement and maxelement functions.
from Calendar cal where maxelement(cal.holidays) > current_date
from Order order where maxindex(order.items) > 100
from Order order where minelement(order.items) > 10000
The SQL functions any, some, all, exists, in are supported when passed the element or
index set of a collection (elements and indices functions) or the result of a subquery (see
below).
Note that these constructs - size, elements, indices, minindex, maxindex, minelement,
maxelement - may only be used in the where clause in Hibernate3.
Elements of indexed collections (arrays, lists, maps) may be referred to by index (in a where
clause only):
HQL also provides the built-in index() function, for elements of a one-to-many association or
collection of values.
If you are not yet convinced by all this, think how much longer and less readable the following
query would be in SQL:
select cust
from Product prod,
Store store
inner join store.customers cust
where prod.name = 'widget'
and store.location.name in ( 'Melbourne', 'Sydney' )
and prod = all elements(cust.currentOrder.lineItems)
Prev Up Next
14.9. The where clause Home 14.11. The order by clause
14.11. The order by clause
Prev Chapter 14. HQL: The Hibernate Query Language Next
Prev Up Next
14.10. Expressions Home 14.12. The group by clause
SQL functions and aggregate functions are allowed in the having and order by clauses, if
supported by the underlying database (eg. not in MySQL).
select cat
from Cat cat
join cat.kittens kitten
group by cat.id, cat.name, cat.other, cat.properties
having avg(kitten.weight) > 100
order by count(kitten) asc, sum(kitten.weight) desc
Note that neither the group by clause nor the order by clause may contain arithmetic
expressions. Also note that Hibernate currently does not expand a grouped entity, so you can't
write group by cat if all properties of cat are non-aggregated. You have to list all non-
aggregated properties explicitly.
Prev Up Next
14.11. The order by clause Home 14.13. Subqueries
14.13. Subqueries
Prev Chapter 14. HQL: The Hibernate Query Language Next
14.13. Subqueries
For databases that support subselects, Hibernate supports subqueries within queries. A subquery
must be surrounded by parentheses (often by an SQL aggregate function call). Even correlated
subqueries (subqueries that refer to an alias in the outer query) are allowed.
Note that HQL subqueries may occur only in the select or where clauses.
Note that subqueries can also utilize row value constructor syntax. See Section 14.18, “Row
value constructor syntax” for more details.
Prev Up Next
14.12. The group by clause Home 14.14. HQL examples
The following query returns the order id, number of items and total value of the order for all
unpaid orders for a particular customer and given minimum total value, ordering the results by
total value. In determining the prices, it uses the current catalog. The resulting SQL query,
against the ORDER, ORDER_LINE, PRODUCT, CATALOG and PRICE tables has four inner joins and an
(uncorrelated) subselect.
What a monster! Actually, in real life, I'm not very keen on subqueries, so my query was really
more like this:
The next query counts the number of payments in each status, excluding all payments in the
AWAITING_APPROVAL status where the most recent status change was made by the current user. It
translates to an SQL query with two inner joins and a correlated subselect against the PAYMENT,
PAYMENT_STATUS and PAYMENT_STATUS_CHANGE tables.
If I would have mapped the statusChanges collection as a list, instead of a set, the query would
have been much simpler to write.
The next query uses the MS SQL Server isNull() function to return all the accounts and unpaid
payments for the organization to which the current user belongs. It translates to an SQL query
with three inner joins, an outer join and a subselect against the ACCOUNT, PAYMENT,
PAYMENT_STATUS, ACCOUNT_TYPE, ORGANIZATION and ORG_USER tables.
For some databases, we would need to do away with the (correlated) subselect.
Prev Up Next
14.13. Subqueries Home 14.15. Bulk update and delete
Prev Up Next
14.14. HQL examples Home 14.16. Tips & Tricks
If your database supports subselects, you can place a condition upon selection size in the where
clause of your query:
Prev Up Next
14.15. Bulk update and delete Home 14.17. Components
14.17. Components
Prev Chapter 14. HQL: The Hibernate Query Language Next
14.17. Components
Components might be used in just about every way that simple value types can be used in HQL
queries. They can appear in the select clause:
where the Person's name property is a component. Components can also be used in the where
clause:
Prev Up Next
14.16. Tips & Tricks Home 14.18. Row value constructor syntax
That's valid syntax, although a little verbose. It be nice to make this a bit more concise and use
row value constructor syntax:
Another time using row value constructor syntax can be beneficial is when using subqueries
needing to compare against multiple values:
One thing to consider when deciding if you want to use this syntax is that the query will be
dependent upon the ordering of the component sub-properties in the metadata.
Prev Up Next
14.17. Components Home Chapter 15. Criteria Queries
Prev Next
14.18. Row value constructor syntax Home 15.2. Narrowing the result set
The {alias} placeholder with be replaced by the row alias of the queried entity.
An alternative approach to obtaining a criterion is to get it from a Property instance. You can
create a Property by calling Property.forName().
Prev Up Next
Chapter 15. Criteria Queries Home 15.3. Ordering the results
Prev Up Next
15.2. Narrowing the result set Home 15.4. Associations
15.4. Associations
Prev Chapter 15. Criteria Queries Next
15.4. Associations
You may easily specify constraints upon related entities by navigating associations using
createCriteria().
note that the second createCriteria() returns a new instance of Criteria, which refers to the
elements of the kittens collection.
Note that the kittens collections held by the Cat instances returned by the previous two queries
are not pre-filtered by the criteria! If you wish to retrieve just the kittens that match the criteria,
you must use a ResultTransformer.
Prev Up Next
15.3. Ordering the results Home 15.5. Dynamic association fetching
This query will fetch both mate and kittens by outer join. See Section 19.1, “Fetching
strategies” for more information.
Prev Up Next
15.4. Associations Home 15.6. Example queries
Version properties, identifiers and associations are ignored. By default, null valued properties are
excluded.
You can even use examples to place criteria upon associated objects.
Prev Up Next
15.5. Dynamic association fetching 15.7. Projections, aggregation and
Home
grouping
There is no explicit "group by" necessary in a criteria query. Certain projection types are defined
to be grouping projections, which also appear in the SQL group by clause.
An alias may optionally be assigned to a projection, so that the projected value may be referred
to in restrictions or orderings. Here are two different ways to do this:
The alias() and as() methods simply wrap a projection instance in another, aliased, instance
of Projection. As a shortcut, you can assign an alias when you add the projection to a
projection list:
Prev Up Next
15.6. Example queries Home 15.8. Detached queries and subqueries
DetachedCriteria avgWeight =
DetachedCriteria.forClass(Cat.class)
.setProjection( Property.forName("weight").avg() );
session.createCriteria(Cat.class)
.add( Property.forName("weight").gt(avgWeight) )
.list();
DetachedCriteria weights = DetachedCriteria.forClass(Cat.class)
.setProjection( Property.forName("weight") );
session.createCriteria(Cat.class)
.add( Subqueries.geAll("weight", weights) )
.list();
Prev Up Next
15.7. Projections, aggregation and 15.9. Queries by natural identifier
Home
grouping
First, you should map the natural key of your entity using <natural-id>, and enable use of the
second-level cache.
<class name="User">
<cache usage="read-write"/>
<id name="id">
<generator class="increment"/>
</id>
<natural-id>
<property name="name"/>
<property name="org"/>
</natural-id>
<property name="password"/>
</class>
Note that this functionality is not intended for use with entities with mutable natural keys.
session.createCriteria(User.class)
.add( Restrictions.naturalId()
.set("name", "gavin")
.set("org", "hb")
).setCacheable(true)
.uniqueResult();
Prev Up Next
15.8. Detached queries and Chapter 16. Native SQL
Home
subqueries
Prev Next
Hibernate3 allows you to specify handwritten SQL (including stored procedures) for all create,
update, delete, and load operations.
This will still return Object arrays, but now it will not use ResultSetMetadata but will instead
explicitly get the ID, NAME and BIRTHDATE column as respectively a Long, String and a
Short from the underlying resultset. This also means that only these three columns will be
returned, even though the query is using * and could return more than the three listed columns.
It is possible to leave out the type information for all or some of the scalars.
This is essentially the same query as before, but now ResultSetMetaData is used to decide the
type of NAME and BIRTHDATE where as the type of ID is explicitly specified.
The above queries were all about returning scalar values, basically returning the "raw" values
from the resultset. The following shows how to get entity objects from a native sql query via
addEntity().
Assuming that Cat is mapped as a class with the columns ID, NAME and BIRTHDATE the
above queries will both return a List where each element is a Cat entity.
If the entity is mapped with a many-to-one to another entity it is required to also return this
when performing the native query, otherwise a database specific "column not found" error will
occur. The additional columns will automatically be returned when using the * notation, but we
prefer to be explicit as in the following example for a many-to-one to a Dog:
It is possible to eagerly join in the Dog to avoid the possible extra roundtrip for initializing the
proxy. This is done via the addJoin() method, which allows you to join in an association or
collection.
In this example the returned Cat's will have their dog property fully initialized without any extra
roundtrip to the database. Notice that we added a alias name ("cat") to be able to specify the
target property path of the join. It is possible to do the same eager joining for collections, e.g. if
the Cat had a one-to-many to Dog instead.
At this stage we are reaching the limits of what is possible with native queries without starting to
enhance the sql queries to make them usable in Hibernate; the problems starts to arise when
returning multiple entities of the same type or when the default alias/column names are not
enough.
Until now the result set column names are assumed to be the same as the column names
specified in the mapping document. This can be problematic for SQL queries which join multiple
tables, since the same column names may appear in more than one table.
Column alias injection is needed in the following query (which most likely will fail):
The intention for this query is to return two Cat instances per row, a cat and its mother. This will
fail since there is a conflict of names since they are mapped to the same column names and on
some databases the returned column aliases will most likely be on the form "c.ID", "c.NAME",
etc. which are not equal to the columns specified in the mappings ("ID" and "NAME").
• the SQL query string, with placeholders for Hibernate to inject column aliases
• the entities returned by the query
The {cat.*} and {mother.*} notation used above is a shorthand for "all properties". Alternatively,
you may list the columns explicitly, but even in this case we let Hibernate inject the SQL column
aliases for each property. The placeholder for a column alias is just the property name qualified
by the table alias. In the following example, we retrieve Cats and their mothers from a different
table (cat_log) to the one declared in the mapping metadata. Notice that we may even use the
property aliases in the where clause if we like.
For most cases the above alias injection is needed, but for queries relating to more complex
mappings like composite properties, inheritance discriminators, collections etc. there are some
specific aliases to use to allow Hibernate to inject the proper aliases.
The following table shows the different possibilities of using the alias injection. Note: the alias
names in the result are examples, each alias will have a unique and probably different name
when used.
Descriptio
Syntax Example
n
A simple
{[aliasname].[propertyname] A_NAME as {item.name}
property
CURRENCY as
A
{[aliasname].[componentname].[propertyname] {item.amount.currency},
composite } VALUE as
property {item.amount.value}
Discrimin
ator of an {[aliasname].class} DISC as {item.class}
entity
All
properties
{[aliasname].*} {item.*}
of an
entity
A
collection {[aliasname].key} ORGID as {coll.key}
key
collection
The
element
{[aliasname].element} XID as {coll.element}
of an
collection
roperty of
the
NAME as
element {[aliasname].element.[propertyname]}
{coll.element.name}
in the
collection
All
properties
of the
{[aliasname].element.*} {coll.element.*}
element
in the
collection
All
properties
{[aliasname].*} {coll.*}
of the the
collection
It is possible to apply a ResultTransformer to native sql queries. Allowing it to e.g. return non-
managed entities.
Native sql queries which query for entities that is mapped as part of an inheritance must include
all properties for the baseclass and all it subclasses.
16.1.7. Parameters
Prev Next
<sql-query name="persons">
<return alias="person" class="eg.Person"/>
SELECT person.NAME AS {person.name},
person.AGE AS {person.age},
person.SEX AS {person.sex}
FROM PERSON person
WHERE person.NAME LIKE :namePattern
</sql-query>
List people = sess.getNamedQuery("persons")
.setString("namePattern", namePattern)
.setMaxResults(50)
.list();
The <return-join> and <load-collection> elements are used to join associations and define
queries which initialize collections, respectively.
<sql-query name="personsWith">
<return alias="person" class="eg.Person"/>
<return-join alias="address"
property="person.mailingAddress"/>
SELECT person.NAME AS {person.name},
person.AGE AS {person.age},
person.SEX AS {person.sex},
address.STREET AS {address.street},
address.CITY AS {address.city},
address.STATE AS {address.state},
address.ZIP AS {address.zip}
FROM PERSON person
JOIN ADDRESS address
ON person.ID = address.PERSON_ID AND
address.TYPE='MAILING'
WHERE person.NAME LIKE :namePattern
</sql-query>
A named SQL query may return a scalar value. You must declare the column alias and Hibernate
type using the <return-scalar> element:
<sql-query name="mySqlQuery">
<return-scalar column="name" type="string"/>
<return-scalar column="age" type="long"/>
SELECT p.NAME AS name,
p.AGE AS age,
FROM PERSON p WHERE p.NAME LIKE 'Hiber%'
</sql-query>
You can externalize the resultset mapping informations in a <resultset> element to either reuse
them across several named queries or through the setResultSetMapping() API.
<resultset name="personAddress">
<return alias="person" class="eg.Person"/>
<return-join alias="address"
property="person.mailingAddress"/>
</resultset>
You can alternatively use the resultset mapping information in your hbm files directly in java
code.
With <return-property> you can explicitly tell Hibernate what column aliases to use, instead
of using the {}-syntax to let Hibernate inject its own aliases.
<sql-query name="mySqlQuery">
<return alias="person" class="eg.Person">
<return-property name="name" column="myName"/>
<return-property name="age" column="myAge"/>
<return-property name="sex" column="mySex"/>
</return>
SELECT person.NAME AS myName,
person.AGE AS myAge,
person.SEX AS mySex,
FROM PERSON person WHERE person.NAME LIKE :name
</sql-query>
<return-property> also works with multiple columns. This solves a limitation with the {}-
syntax which can not allow fine grained control of multi-column properties.
<sql-query name="organizationCurrentEmployments">
<return alias="emp" class="Employment">
<return-property name="salary">
<return-column name="VALUE"/>
<return-column name="CURRENCY"/>
</return-property>
<return-property name="endDate" column="myEndDate"/>
</return>
SELECT EMPLOYEE AS {emp.employee}, EMPLOYER AS
{emp.employer},
STARTDATE AS {emp.startDate}, ENDDATE AS {emp.endDate},
REGIONCODE as {emp.regionCode}, EID AS {emp.id}, VALUE,
CURRENCY
FROM EMPLOYMENT
WHERE EMPLOYER = :id AND ENDDATE IS NULL
ORDER BY STARTDATE ASC
</sql-query>
Notice that in this example we used <return-property> in combination with the {}-syntax for
injection. Allowing users to choose how they want to refer column and properties.
If your mapping has a discriminator you must use <return-discriminator> to specify the
discriminator column.
Hibernate 3 introduces support for queries via stored procedures and functions. Most of the
following documentation is equivalent for both. The stored procedure/function must return a
resultset as the first out-parameter to be able to work with Hibernate. An example of such a
stored function in Oracle 9 and higher is as follows:
To use this query in Hibernate you need to map it via a named query.
Notice stored procedures currently only return scalars and entities. <return-join> and <load-
collection> are not supported.
To use stored procedures with Hibernate the procedures/functions have to follow some rules. If
they do not follow those rules they are not usable with Hibernate. If you still want to use these
procedures you have to execute them via session.connection(). The rules are different for
each database, since database vendors have different stored procedure semantics/syntax.
• A function must return a result set. The first parameter of a procedure must be an OUT that returns
a result set. This is done by using a SYS_REFCURSOR type in Oracle 9 or 10. In Oracle you need to
define a REF CURSOR type, see Oracle literature.
For Sybase or MS SQL server the following rules apply:
• The procedure must return a result set. Note that since these servers can/will return multiple
result sets and update counts, Hibernate will iterate the results and take the first result that is a
result set as its return value. Everything else will be discarded.
• If you can enable SET NOCOUNT ON in your procedure it will probably be more efficient, but this
is not a requirement.
Prev Up Next
<class name="Person">
<id name="id">
<generator class="increment"/>
</id>
<property name="name" not-null="true"/>
<sql-insert>INSERT INTO PERSON (NAME, ID) VALUES
( UPPER(?), ? )</sql-insert>
<sql-update>UPDATE PERSON SET NAME=UPPER(?) WHERE
ID=?</sql-update>
<sql-delete>DELETE FROM PERSON WHERE ID=?</sql-delete>
</class>
The SQL is directly executed in your database, so you are free to use any dialect you like. This
will of course reduce the portability of your mapping if you use database specific SQL.
<class name="Person">
<id name="id">
<generator class="increment"/>
</id>
<property name="name" not-null="true"/>
<sql-insert callable="true">{call createPerson (?, ?)}
</sql-insert>
<sql-delete callable="true">{? = call deletePerson
(?)}</sql-delete>
<sql-update callable="true">{? = call updatePerson (?, ?)}
</sql-update>
</class>
The order of the positional parameters are currently vital, as they must be in the same sequence
as Hibernate expects them.
You can see the expected order by enabling debug logging for the
org.hibernate.persister.entity level. With this level enabled Hibernate will print out the
static SQL that is used to create, update, delete etc. entities. (To see the expected sequence,
remember to not include your custom SQL in the mapping files as that will override the
Hibernate generated static sql.)
The stored procedures are in most cases (read: better do it than not) required to return the number
of rows inserted/updated/deleted, as Hibernate has some runtime checks for the success of the
statement. Hibernate always registers the first statement parameter as a numeric output parameter
for the CUD operations:
update PERSON
set
NAME = uname,
where
ID = uid;
return SQL%ROWCOUNT;
END updatePerson;
Prev Up Next
16.2. Named SQL queries Home 16.4. Custom SQL for loading
16.4. Custom SQL for loading
Prev Chapter 16. Native SQL Next
<sql-query name="person">
<return alias="pers" class="Person" lock-mode="upgrade"/>
SELECT NAME AS {pers.name}, ID AS {pers.id}
FROM PERSON
WHERE ID=?
FOR UPDATE
</sql-query>
This is just a named query declaration, as discussed earlier. You may reference this named query
in a class mapping:
<class name="Person">
<id name="id">
<generator class="increment"/>
</id>
<property name="name" not-null="true"/>
<loader query-ref="person"/>
</class>
<sql-query name="person">
<return alias="pers" class="Person"/>
<return-join alias="emp" property="pers.employments"/>
SELECT NAME AS {pers.*}, {emp.*}
FROM PERSON pers
LEFT OUTER JOIN EMPLOYMENT emp
ON pers.ID = emp.PERSON_ID
WHERE ID=?
</sql-query>
Prev Up Next
16.3. Custom SQL for create, update Chapter 17. Filtering data
Home
and delete
In order to use filters, they must first be defined and then attached to the appropriate mapping
elements. To define a filter, use the <filter-def/> element within a <hibernate-mapping/>
element:
<filter-def name="myFilter">
<filter-param name="myFilterParam" type="string"/>
</filter-def>
Then, this filter can be attached to a class:
or, to a collection:
<set ...>
<filter name="myFilter" condition=":myFilterParam =
MY_FILTERED_COLUMN"/>
</set>
session.enableFilter("myFilter").setParameter("myFilterParam",
"some-value");
Note that methods on the org.hibernate.Filter interface do allow the method-chaining common to
much of Hibernate.
A full example, using temporal data with an effective record date pattern:
<filter-def name="effectiveDate">
<filter-param name="asOfDate" type="date"/>
</filter-def>
Then, in order to ensure that you always get back currently effective records, simply enable the
filter on the session prior to retrieving employee data:
In the HQL above, even though we only explicitly mentioned a salary constraint on the results,
because of the enabled filter the query will return only currently active employees who have a
salary greater than a million dollars.
Note: if you plan on using filters with outer joining (either through HQL or load fetching) be
careful of the direction of the condition expression. Its safest to set this up for left outer joining;
in general, place the parameter first followed by the column name(s) after the operator.
After being defined a filter might be attached to multiple entities and/or collections each with its
own condition. That can be tedious when the conditions are the same each time. Thus <filter-
def/> allows defining a default condition, either as an attribute or CDATA:
<filter-def name="myFilter" condition="abc > xyz">...</filter-
def>
<filter-def name="myOtherFilter">abc=xyz</filter-def>
This default condition will then be used whenever the filter is attached to something without
specifying a condition. Note that this means you can give a specific condition as part of the
attachment of the filter which overrides the default condition in that particular case.
Prev Next
16.4. Custom SQL for loading Home Chapter 18. XML Mapping
Prev Next
Hibernate supports dom4j as API for manipulating XML trees. You can write queries that
retrieve dom4j trees from the database and have any modification you make to the tree
automatically synchronized to the database. You can even take an XML document, parse it using
dom4j, and write it to the database with any of Hibernate's basic operations: persist(),
saveOrUpdate(), merge(), delete(), replicate() (merging is not yet supported).
This feature has many applications including data import/export, externalization of entity data
via JMS or SOAP and XSLT-based reporting.
A single mapping may be used to simultaneously map properties of a class and nodes of an XML
document to the database, or, if there is no class to map, it may be used to map just the XML.
18.1.1. Specifying XML and class mapping together
<class name="Account"
table="ACCOUNTS"
node="account">
<id name="accountId"
column="ACCOUNT_ID"
node="@id"/>
<many-to-one name="customer"
column="CUSTOMER_ID"
node="customer/@id"
embed-xml="false"/>
<property name="balance"
column="BALANCE"
node="balance"/>
...
</class>
<class entity-name="Account"
table="ACCOUNTS"
node="account">
<id name="id"
column="ACCOUNT_ID"
node="@id"
type="string"/>
<many-to-one name="customerId"
column="CUSTOMER_ID"
node="customer/@id"
embed-xml="false"
entity-name="Customer"/>
<property name="balance"
column="BALANCE"
node="balance"
type="big_decimal"/>
...
</class>
This mapping allows you to access the data as a dom4j tree, or as a graph of property name/value
pairs (java Maps). The property names are purely logical constructs that may be referred to in
HQL queries.
Prev Next
For collections and single valued associations, there is an additional embed-xml attribute. If
embed-xml="true", the default, the XML tree for the associated entity (or collection of value
type) will be embedded directly in the XML tree for the entity that owns the association.
Otherwise, if embed-xml="false", then only the referenced identifier value will appear in the
XML for single point associations and collections will simply not appear at all.
You should be careful not to leave embed-xml="true" for too many associations, since XML
does not deal well with circularity!
<class name="Customer"
table="CUSTOMER"
node="customer">
<id name="id"
column="CUST_ID"
node="@id"/>
<map name="accounts"
node="."
embed-xml="true">
<key column="CUSTOMER_ID"
not-null="true"/>
<map-key column="SHORT_DESC"
node="@short-desc"
type="string"/>
<one-to-many entity-name="Account"
embed-xml="false"
node="account"/>
</map>
<component name="name"
node="name">
<property name="firstName"
node="first-name"/>
<property name="initial"
node="initial"/>
<property name="lastName"
node="last-name"/>
</component>
...
</class>
in this case, we have decided to embed the collection of account ids, but not the actual account
data. The following HQL query:
<customer id="123456789">
<account short-desc="Savings">987632567</account>
<account short-desc="Credit Card">985612323</account>
<name>
<first-name>Gavin</first-name>
<initial>A</initial>
<last-name>King</last-name>
</name>
...
</customer>
If you set embed-xml="true" on the <one-to-many> mapping, the data might look more like
this:
<customer id="123456789">
<account id="987632567" short-desc="Savings">
<customer id="123456789"/>
<balance>100.29</balance>
</account>
<account id="985612323" short-desc="Credit Card">
<customer id="123456789"/>
<balance>-2370.34</balance>
</account>
<name>
<first-name>Gavin</first-name>
<initial>A</initial>
<last-name>King</last-name>
</name>
...
</customer>
Prev Up Next
Chapter 18. XML Mapping Home 18.3. Manipulating XML data
18.3. Manipulating XML data
tx.commit();
session.close();
Session session = factory.openSession();
Session dom4jSession = session.getSession(EntityMode.DOM4J);
Transaction tx = session.beginTransaction();
tx.commit();
session.close();
Prev Up Next
18.2. XML mapping metadata Home Chapter 19. Improving performance
Prev Next
• Join fetching - Hibernate retrieves the associated instance or collection in the same SELECT,
using an OUTER JOIN.
• Select fetching - a second SELECT is used to retrieve the associated entity or collection. Unless
you explicitly disable lazy fetching by specifying lazy="false", this second select will only be
executed when you actually access the association.
• Subselect fetching - a second SELECT is used to retrieve the associated collections for all entities
retrieved in a previous query or fetch. Unless you explicitly disable lazy fetching by specifying
lazy="false", this second select will only be executed when you actually access the
association.
• Batch fetching - an optimization strategy for select fetching - Hibernate retrieves a batch of entity
instances or collections in a single SELECT, by specifying a list of primary keys or foreign keys.
We have two orthogonal notions here: when is the association fetched, and how is it fetched
(what SQL is used). Don't confuse them! We use fetch to tune performance. We may use lazy
to define a contract for what data is always available in any detached instance of a particular
class.
19.1.1. Working with lazy associations
By default, Hibernate3 uses lazy select fetching for collections and lazy proxy fetching for
single-valued associations. These defaults make sense for almost all associations in almost all
applications.
Note: if you set hibernate.default_batch_fetch_size, Hibernate will use the batch fetch
optimization for lazy fetching (this optimization may also be enabled at a more granular level).
However, lazy fetching poses one problem that you must be aware of. Access to a lazy
association outside of the context of an open Hibernate session will result in an exception. For
example:
s = sessions.openSession();
Transaction tx = s.beginTransaction();
tx.commit();
s.close();
Since the permissions collection was not initialized when the Session was closed, the collection
will not be able to load its state. Hibernate does not support lazy initialization for detached
objects. The fix is to move the code that reads from the collection to just before the transaction is
committed.
On the other hand, we often want to choose join fetching (which is non-lazy by nature) instead of
select fetching in a particular transaction. We'll now see how to customize the fetching strategy.
In Hibernate3, the mechanisms for choosing a fetch strategy are identical for single-valued
associations and collections.
Select fetching (the default) is extremely vulnerable to N+1 selects problems, so we might want
to enable join fetching in the mapping document:
<set name="permissions"
fetch="join">
<key column="userId"/>
<one-to-many class="Permission"/>
</set
<many-to-one name="mother" class="Cat" fetch="join"/>
No matter what fetching strategy you use, the defined non-lazy graph is guaranteed to be loaded
into memory. Note that this might result in several immediate selects being used to execute a
particular HQL query.
Usually, we don't use the mapping document to customize fetching. Instead, we keep the default
behavior, and override it for a particular transaction, using left join fetch in HQL. This tells
Hibernate to fetch the association eagerly in the first select, using an outer join. In the Criteria
query API, you would use setFetchMode(FetchMode.JOIN).
If you ever feel like you wish you could change the fetching strategy used by get() or load(),
simply use a Criteria query, for example:
(This is Hibernate's equivalent of what some ORM solutions call a "fetch plan".)
A completely different way to avoid problems with N+1 selects is to use the second-level cache.
Lazy fetching for collections is implemented using Hibernate's own implementation of persistent
collections. However, a different mechanism is needed for lazy behavior in single-ended
associations. The target entity of the association must be proxied. Hibernate implements lazy
initializing proxies for persistent objects using runtime bytecode enhancement (via the excellent
CGLIB library).
By default, Hibernate3 generates proxies (at startup) for all persistent classes and uses them to
enable lazy fetching of many-to-one and one-to-one associations.
The mapping file may declare an interface to use as the proxy interface for that class, with the
proxy attribute. By default, Hibernate uses a subclass of the class. Note that the proxied class
must implement a default constructor with at least package visibility. We recommend this
constructor for all persistent classes!
There are some gotchas to be aware of when extending this approach to polymorphic classes, eg.
Firstly, instances of Cat will never be castable to DomesticCat, even if the underlying instance
is an instance of DomesticCat:
However, the situation is not quite as bad as it looks. Even though we now have two references
to different proxy objects, the underlying instance will still be the same object:
Third, you may not use a CGLIB proxy for a final class or a class with any final methods.
Finally, if your persistent object acquires any resources upon instantiation (eg. in initializers or
default constructor), then those resources will also be acquired by the proxy. The proxy class is
an actual subclass of the persistent class.
These problems are all due to fundamental limitations in Java's single inheritance model. If you
wish to avoid these problems your persistent classes must each implement an interface that
declares its business methods. You should specify these interfaces in the mapping file. eg.
where CatImpl implements the interface Cat and DomesticCatImpl implements the interface
DomesticCat. Then proxies for instances of Cat and DomesticCat may be returned by load()
or iterate(). (Note that list() does not usually return proxies.)
Relationships are also lazily initialized. This means you must declare any properties to be of type
Cat, not CatImpl.
By choosing lazy="no-proxy" instead of the default lazy="proxy", we can avoid the problems
associated with typecasting. However, we will require buildtime bytecode instrumentation, and
all operations will result in immediate proxy initialization.
Another option is to keep the Session open until all needed collections and proxies have been
loaded. In some application architectures, particularly where the code that accesses data using
Hibernate, and the code that uses it are in different application layers or different physical
processes, it can be a problem to ensure that the Session is open when a collection is initialized.
There are two basic ways to deal with this issue:
• In a web-based application, a servlet filter can be used to close the Session only at the very end
of a user request, once the rendering of the view is complete (the Open Session in View pattern).
Of course, this places heavy demands on the correctness of the exception handling of your
application infrastructure. It is vitally important that the Session is closed and the transaction
ended before returning to the user, even when an exception occurs during rendering of the view.
See the Hibernate Wiki for examples of this "Open Session in View" pattern.
• In an application with a separate business tier, the business logic must "prepare" all collections
that will be needed by the web tier before returning. This means that the business tier should load
all the data and return all the data already initialized to the presentation/web tier that is required
for a particular use case. Usually, the application calls Hibernate.initialize() for each
collection that will be needed in the web tier (this call must occur before the session is closed) or
retrieves the collection eagerly using a Hibernate query with a FETCH clause or a
FetchMode.JOIN in Criteria. This is usually easier if you adopt the Command pattern instead
of a Session Facade.
• You may also attach a previously loaded object to a new Session with merge() or lock()
before accessing uninitialized collections (or other proxies). No, Hibernate does not, and
certainly should not do this automatically, since it would introduce ad hoc transaction semantics!
Sometimes you don't want to initialize a large collection, but still need some information about it
(like its size) or a subset of the data.
You can use a collection filter to get the size of a collection without initializing it:
The createFilter() method is also used to efficiently retrieve subsets of a collection without
needing to initialize the whole collection:
s.createFilter( lazyCollection,
"").setFirstResult(0).setMaxResults(10).list();
Hibernate can make efficient use of batch fetching, that is, Hibernate can load several
uninitialized proxies if one proxy is accessed (or collections. Batch fetching is an optimization of
the lazy select fetching strategy. There are two ways you can tune batch fetching: on the class
and the collection level.
Batch fetching for classes/entities is easier to understand. Imagine you have the following
situation at runtime: You have 25 Cat instances loaded in a Session, each Cat has a reference to
its owner, a Person. The Person class is mapped with a proxy, lazy="true". If you now iterate
through all cats and call getOwner() on each, Hibernate will by default execute 25 SELECT
statements, to retrieve the proxied owners. You can tune this behavior by specifying a batch-
size in the mapping of Person:
Hibernate will now execute only three queries, the pattern is 10, 10, 5.
You may also enable batch fetching of collections. For example, if each Person has a lazy
collection of Cats, and 10 persons are currently loaded in the Session, iterating through all
persons will generate 10 SELECTs, one for every call to getCats(). If you enable batch fetching
for the cats collection in the mapping of Person, Hibernate can pre-fetch collections:
<class name="Person">
<set name="cats" batch-size="3">
...
</set>
</class>
With a batch-size of 3, Hibernate will load 3, 3, 3, 1 collections in four SELECTs. Again, the
value of the attribute depends on the expected number of uninitialized collections in a particular
Session.
Batch fetching of collections is particularly useful if you have a nested tree of items, ie. the
typical bill-of-materials pattern. (Although a nested set or a materialized path might be a better
option for read-mostly trees.)
19.1.6. Using subselect fetching
If one lazy collection or single-valued proxy has to be fetched, Hibernate loads all of them, re-
running the original query in a subselect. This works in the same way as batch-fetching, without
the piecemeal loading.
Hibernate3 supports the lazy fetching of individual properties. This optimization technique is
also known as fetch groups. Please note that this is mostly a marketing feature, as in practice,
optimizing row reads is much more important than optimization of column reads. However, only
loading some properties of a class might be useful in extreme cases, when legacy tables have
hundreds of columns and the data model can not be improved.
To enable lazy property loading, set the lazy attribute on your particular property mappings:
<class name="Document">
<id name="id">
<generator class="native"/>
</id>
<property name="name" not-null="true" length="50"/>
<property name="summary" not-null="true" length="200"
lazy="true"/>
<property name="text" not-null="true" length="2000"
lazy="true"/>
</class>
Lazy property loading requires buildtime bytecode instrumentation! If your persistent classes are
not enhanced, Hibernate will silently ignore lazy property settings and fall back to immediate
fetching.
<instrument verbose="true">
<fileset
dir="${testclasses.dir}/org/hibernate/auction/model">
<include name="*.class"/>
</fileset>
</instrument>
</target>
A different (better?) way to avoid unnecessary column reads, at least for read-only transactions is
to use the projection features of HQL or Criteria queries. This avoids the need for buildtime
bytecode processing and is certainly a preferred solution.
You may force the usual eager fetching of properties using fetch all properties in HQL.
Prev Next
18.3. Manipulating XML data Home 19.2. The Second Level Cache
You have the option to tell Hibernate which caching implementation to use by specifying the
name of a class that implements org.hibernate.cache.CacheProvider using the property
hibernate.cache.provider_class. Hibernate comes bundled with a number of built-in
integrations with open-source cache providers (listed below); additionally, you could implement
your own and plug it in as outlined above. Note that versions prior to 3.2 defaulted to use
EhCache as the default cache provider; that is no longer the case as of 3.2.
Hashtabl
e (not
intended
org.hibernate.cache.HashtableCacheProvider memory yes
for
producti
on use)
memory,
EHCache org.hibernate.cache.EhCacheProvider yes
disk
OSCach memory,
org.hibernate.cache.OSCacheProvider yes
e disk
yes
clustered (clustere
SwarmC
org.hibernate.cache.SwarmCacheProvider (ip d
ache
multicast) invalidati
on)
clustered
(ip yes
JBoss yes
multicast) (clock
Cache org.hibernate.cache.TreeCacheProvider (replicati
, sync
1.x on)
transactio req.)
nal
clustered
yes
(ip yes
(replicati
JBoss org.hibernate.cache.jbc2.JBossCacheRegionF multicast) (clock
on or
Cache 2 actory , sync
invalidati
transactio req.)
on)
nal
19.2.1. Cache mappings
The <cache> element of a class or collection mapping has the following form:
<cache
usage="transactional|read-write|nonstrict-read-write|read-
only" (1)
region="RegionName"
(2)
include="all|non-lazy"
(3)
/>
(1) usage (required) specifies the caching strategy: transactional, read-write, nonstrict-
read-write or read-only
(2) region (optional, defaults to the class or collection role name) specifies the name of the
second level cache region
(3) include (optional, defaults to all) non-lazy specifies that properties of the entity mapped
with lazy="true" may not be cached when attribute-level lazy fetching is enabled
If your application needs to read but never modify instances of a persistent class, a read-only
cache may be used. This is the simplest and best performing strategy. It's even perfectly safe for
use in a cluster.
If the application needs to update data, a read-write cache might be appropriate. This cache
strategy should never be used if serializable transaction isolation level is required. If the cache is
used in a JTA environment, you must specify the property
hibernate.transaction.manager_lookup_class, naming a strategy for obtaining the JTA
TransactionManager. In other environments, you should ensure that the transaction is
completed when Session.close() or Session.disconnect() is called. If you wish to use this
strategy in a cluster, you should ensure that the underlying cache implementation supports
locking. The built-in cache providers do not.
If the application only occasionally needs to update data (ie. if it is extremely unlikely that two
transactions would try to update the same item simultaneously) and strict transaction isolation is
not required, a nonstrict-read-write cache might be appropriate. If the cache is used in a JTA
environment, you must specify hibernate.transaction.manager_lookup_class. In other
environments, you should ensure that the transaction is completed when Session.close() or
Session.disconnect() is called.
The transactional cache strategy provides support for fully transactional cache providers such
as JBoss TreeCache. Such a cache may only be used in a JTA environment and you must specify
hibernate.transaction.manager_lookup_class.
Important
None of the cache providers support all of the cache concurrency strategies.
The following table shows which providers are compatible with which concurrency strategies.
Prev Up Next
When flush() is subsequently called, the state of that object will be synchronized with the
database. If you do not want this synchronization to occur or if you are processing a huge
number of objects and need to manage memory efficiently, the evict() method may be used to
remove the object and its collections from the first-level cache.
The Session also provides a contains() method to determine if an instance belongs to the
session cache.
To completely evict all objects from the session cache, call Session.clear()
For the second-level cache, there are methods defined on SessionFactory for evicting the
cached state of an instance, entire class, collection instance or entire collection role.
The CacheMode controls how a particular session interacts with the second-level cache.
• CacheMode.NORMAL - read items from and write items to the second-level cache
• CacheMode.GET - read items from the second-level cache, but don't write to the second-level
cache except when updating data
• CacheMode.PUT - write items to the second-level cache, but don't read from the second-level
cache
• CacheMode.REFRESH - write items to the second-level cache, but don't read from the second-
level cache, bypass the effect of hibernate.cache.use_minimal_puts, forcing a refresh of the
second-level cache for all items read from the database
To browse the contents of a second-level or query cache region, use the Statistics API:
You'll need to enable statistics, and, optionally, force Hibernate to keep the cache entries in a
more human-understandable format:
hibernate.generate_statistics true
hibernate.cache.use_structured_entries true
Prev Up Next
19.2. The Second Level Cache Home 19.4. The Query Cache
hibernate.cache.use_query_cache true
This setting causes the creation of two new cache regions - one holding cached query result sets
(org.hibernate.cache.StandardQueryCache), the other holding timestamps of the most
recent updates to queryable tables (org.hibernate.cache.UpdateTimestampsCache). Note
that the query cache does not cache the state of the actual entities in the result set; it caches only
identifier values and results of value type. So the query cache should always be used in
conjunction with the second-level cache.
Most queries do not benefit from caching, so by default queries are not cached. To enable
caching, call Query.setCacheable(true). This call allows the query to look for existing cache
results or add its results to the cache when it is executed.
If you require fine-grained control over query cache expiration policies, you may specify a
named cache region for a particular query by calling Query.setCacheRegion().
If the query should force a refresh of its query cache region, you should call
Query.setCacheMode(CacheMode.REFRESH). This is particularly useful in cases where
underlying data may have been updated via a separate process (i.e., not modified through
Hibernate) and allows the application to selectively refresh particular query result sets. This is a
more efficient alternative to eviction of a query cache region via
SessionFactory.evictQueries().
Prev Up Next
19.3. Managing the caches 19.5. Understanding Collection
Home
performance
19.5.1. Taxonomy
• collections of values
• one to many associations
• many to many associations
This classification distinguishes the various table and foreign key relationships but does not tell
us quite everything we need to know about the relational model. To fully understand the
relational structure and performance characteristics, we must also consider the structure of the
primary key that is used by Hibernate to update or delete collection rows. This suggests the
following classification:
• indexed collections
• sets
• bags
All indexed collections (maps, lists, arrays) have a primary key consisting of the <key> and
<index> columns. In this case collection updates are usually extremely efficient - the primary
key may be efficiently indexed and a particular row may be efficiently located when Hibernate
tries to update or delete it.
Sets have a primary key consisting of <key> and element columns. This may be less efficient for
some types of collection element, particularly composite elements or large text or binary fields;
the database may not be able to index a complex primary key as efficiently. On the other hand,
for one to many or many to many associations, particularly in the case of synthetic identifiers, it
is likely to be just as efficient. (Side-note: if you want SchemaExport to actually create the
primary key of a <set> for you, you must declare all columns as not-null="true".)
<idbag> mappings define a surrogate key, so they are always very efficient to update. In fact,
they are the best case.
Bags are the worst case. Since a bag permits duplicate element values and has no index column,
no primary key may be defined. Hibernate has no way of distinguishing between duplicate rows.
Hibernate resolves this problem by completely removing (in a single DELETE) and recreating the
collection whenever it changes. This might be very inefficient.
Note that for a one-to-many association, the "primary key" may not be the physical primary key
of the database table - but even in this case, the above classification is still useful. (It still reflects
how Hibernate "locates" individual rows of the collection.)
19.5.2. Lists, maps, idbags and sets are the most efficient collections to
update
From the discussion above, it should be clear that indexed collections and (usually) sets allow the
most efficient operation in terms of adding, removing and updating elements.
There is, arguably, one more advantage that indexed collections have over sets for many to many
associations or collections of values. Because of the structure of a Set, Hibernate doesn't ever
UPDATE a row when an element is "changed". Changes to a Set always work via INSERT and
DELETE (of individual rows). Once again, this consideration does not apply to one to many
associations.
After observing that arrays cannot be lazy, we would conclude that lists, maps and idbags are the
most performant (non-inverse) collection types, with sets not far behind. Sets are expected to be
the most common kind of collection in Hibernate applications. This is because the "set"
semantics are most natural in the relational model.
However, in well-designed Hibernate domain models, we usually see that most collections are in
fact one-to-many associations with inverse="true". For these associations, the update is
handled by the many-to-one end of the association, and so considerations of collection update
performance simply do not apply.
19.5.3. Bags and lists are the most efficient inverse collections
Just before you ditch bags forever, there is a particular case in which bags (and also lists) are
much more performant than sets. For a collection with inverse="true" (the standard
bidirectional one-to-many relationship idiom, for example) we can add elements to a bag or list
without needing to initialize (fetch) the bag elements! This is because Collection.add() or
Collection.addAll() must always return true for a bag or List (unlike a Set). This can make
the following common code much faster.
Parent p = (Parent) sess.load(Parent.class, id);
Child c = new Child();
c.setParent(p);
p.getChildren().add(c); //no need to fetch the collection!
sess.flush();
Occasionally, deleting collection elements one by one can be extremely inefficient. Hibernate
isn't completely stupid, so it knows not to do that in the case of an newly-empty collection (if
you called list.clear(), for example). In this case, Hibernate will issue a single DELETE and
we are done!
Suppose we add a single element to a collection of size twenty and then remove two elements.
Hibernate will issue one INSERT statement and two DELETE statements (unless the collection is a
bag). This is certainly desirable.
However, suppose that we remove eighteen elements, leaving two and then add thee new
elements. There are two possible ways to proceed
• delete eighteen rows one by one and then insert three rows
• remove the whole collection (in one SQL DELETE) and insert all five current elements (one by
one)
Hibernate isn't smart enough to know that the second option is probably quicker in this case.
(And it would probably be undesirable for Hibernate to be that smart; such behaviour might
confuse database triggers, etc.)
Fortunately, you can force this behaviour (ie. the second strategy) at any time by discarding (ie.
dereferencing) the original collection and returning a newly instantiated collection with all the
current elements. This can be very useful and powerful from time to time.
Prev Up Next
You can access SessionFactory metrics in two ways. Your first option is to call
sessionFactory.getStatistics() and read or display the Statistics yourself.
Hibernate can also use JMX to publish metrics if you enable the StatisticsService MBean.
You may enable a single MBean for all your SessionFactory or one per factory. See the
following code for minimalistic configuration examples:
• at runtime: sf.getStatistics().setStatisticsEnabled(true) or
hibernateStatsBean.setStatisticsEnabled(true)
Statistics can be reset programmatically using the clear() method. A summary can be sent to a
logger (info level) using the logSummary() method.
19.6.2. Metrics
Hibernate provides a number of metrics, from very basic to the specialized information only
relevant in certain scenarios. All available counters are described in the Statistics interface
API, in three categories:
• Metrics related to the general Session usage, such as number of open sessions, retrieved JDBC
connections, etc.
• Metrics related to he entities, collections, queries, and caches as a whole (aka global metrics),
• Detailed metrics related to a particular entity, collection, query or cache region.
For example, you can check the cache hit, miss, and put ratio of entities, collections and queries,
and the average time a query needs. Beware that the number of milliseconds is subject to
approximation in Java. Hibernate is tied to the JVM precision, on some platforms this might
even only be accurate to 10 seconds.
Simple getters are used to access the global metrics (i.e. not tied to a particular entity, collection,
cache region, etc.). You can access the metrics of a particular entity, collection or cache region
through its name, and through its HQL or SQL representation for queries. Please refer to the
Statistics, EntityStatistics, CollectionStatistics, SecondLevelCacheStatistics,
and QueryStatistics API Javadoc for more information. The following code shows a simple
example:
Statistics stats =
HibernateUtil.sessionFactory.getStatistics();
EntityStatistics entityStats =
stats.getEntityStatistics( Cat.class.getName() );
long changes =
entityStats.getInsertCount()
+ entityStats.getUpdateCount()
+ entityStats.getDeleteCount();
log.info(Cat.class.getName() + " changed " + changes + "times"
);
To work on all entities, collections, queries and region caches, you can retrieve the list of names
of entities, collections, queries and region caches with the following methods: getQueries(),
getEntityNames(), getCollectionRoleNames(), and getSecondLevelCacheRegionNames().
Prev Up Next
Prev Next
The Hibernate Tools currently include plugins for the Eclipse IDE as well as Ant tasks for
reverse engineering of existing databases:
• Mapping Editor: An editor for Hibernate XML mapping files, supporting auto-completion and
syntax highlighting. It also supports semantic auto-completion for class names and property/field
names, making it much more versatile than a normal XML editor.
• Console: The console is a new view in Eclipse. In addition to a tree overview of your console
configurations, you also get an interactive view of your persistent classes and their relationships.
The console allows you to execute HQL queries against your database and browse the result
directly in Eclipse.
• Development Wizards: Several wizards are provided with the Hibernate Eclipse tools; you can
use a wizard to quickly generate Hibernate configuration (cfg.xml) files, or you may even
completely reverse engineer an existing database schema into POJO source files and Hibernate
mapping files. The reverse engineering wizard supports customizable templates.
• Ant Tasks:
Please refer to the Hibernate Tools package and it's documentation for more information.
However, the Hibernate main package comes bundled with an integrated tool (it can even be
used from "inside" Hibernate on-the-fly): SchemaExport aka hbm2ddl.
You must specify a SQL Dialect via the hibernate.dialect property when using this tool, as
DDL is highly vendor specific.
Many Hibernate mapping elements define optional attributes named length, precision and
scale. You may set the length, precision and scale of a column with this attribute.
Some tags also accept a not-null attribute (for generating a NOT NULL constraint on table
columns) and a unique attribute (for generating UNIQUE constraint on table columns).
A unique-key attribute may be used to group columns in a single unique key constraint.
Currently, the specified value of the unique-key attribute is not used to name the constraint in
the generated DDL, only to group the columns in the mapping file.
A foreign-key attribute may be used to override the name of any generated foreign key
constraint.
Many mapping elements also accept a child <column> element. This is particularly useful for
mapping multi-column types:
The default attribute lets you specify a default value for a column (you should assign the same
value to the mapped property before saving a new instance of the mapped class).
The sql-type attribute allows the user to override the default mapping of a Hibernate type to
SQL datatype.
table
The <comment> element allows you to specify comments for the generated schema.
This results in a comment on table or comment on column statement in the generated DDL
(where supported).
The SchemaExport tool writes a DDL script to standard out and/or executes the DDL statements.
Option Description
20.1.3. Properties
jdbc driver
hibernate.connection.driver_class
class
hibernate.dialect dialect
<target name="schemaexport">
<taskdef name="schemaexport"
classname="org.hibernate.tool.hbm2ddl.SchemaExportTask"
classpathref="class.path"/>
<schemaexport
properties="hibernate.properties"
quiet="no"
text="no"
drop="no"
delimiter=";"
output="schema-export.sql">
<fileset dir="src">
<include name="**/*.hbm.xml"/>
</fileset>
</schemaexport>
</target>
The SchemaUpdate tool will update an existing schema with "incremental" changes. Note that
SchemaUpdate depends heavily upon the JDBC metadata API, so it will not work with all JDBC
drivers.
<target name="schemaupdate">
<taskdef name="schemaupdate"
classname="org.hibernate.tool.hbm2ddl.SchemaUpdateTask"
classpathref="class.path"/>
<schemaupdate
properties="hibernate.properties"
quiet="no">
<fileset dir="src">
<include name="**/*.hbm.xml"/>
</fileset>
</schemaupdate>
</target>
20.1.7. Schema validation
The SchemaValidator tool will validate that the existing database schema "matches" your
mapping documents. Note that SchemaValidator depends heavily upon the JDBC metadata
API, so it will not work with all JDBC drivers. This tool is extremely useful for testing.
Option Description
<target name="schemavalidate">
<taskdef name="schemavalidator"
classname="org.hibernate.tool.hbm2ddl.SchemaValidatorTa
sk"
classpathref="class.path"/>
<schemavalidator
properties="hibernate.properties">
<fileset dir="src">
<include name="**/*.hbm.xml"/>
</fileset>
</schemavalidator>
</target>
Prev Next
• When we remove / add an object from / to a collection, the version number of the collection
owner is incremented.
• If an object that was removed from a collection is an instance of a value type (eg, a composite
element), that object will cease to be persistent and its state will be completely removed from the
database. Likewise, adding a value type instance to the collection will cause its state to be
immediately persistent.
• On the other hand, if an entity is removed from a collection (a one-to-many or many-to-many
association), it will not be deleted, by default. This behaviour is completely consistent - a change
to the internal state of another entity should not cause the associated entity to vanish! Likewise,
adding an entity to a collection does not cause that entity to become persistent, by default.
Instead, the default behaviour is that adding an entity to a collection merely creates a link
between the two entities, while removing it removes the link. This is very appropriate for all
sorts of cases. Where it is not appropriate at all is the case of a parent / child relationship, where
the life of the child is bound to the life cycle of the parent.
Prev Next
Chapter 20. Toolset Guide Home 21.2. Bidirectional one-to-many
<set name="children">
<key column="parent_id"/>
<one-to-many class="Child"/>
</set>
Parent p = .....;
Child c = new Child();
p.getChildren().add(c);
session.save(c);
session.flush();
This is not only inefficient, but also violates any NOT NULL constraint on the parent_id column.
We can fix the nullability constraint violation by specifying not-null="true" in the collection
mapping:
<set name="children">
<key column="parent_id" not-null="true"/>
<one-to-many class="Child"/>
</set>
(We also need to add the parent property to the Child class.)
Now that the Child entity is managing the state of the link, we tell the collection not to update
the link. We use the inverse attribute.
Prev Up Next
Chapter 21. Example: Parent/Child Home 21.3. Cascading life cycle
Similarly, we don't need to iterate over the children when saving or deleting a Parent. The
following removes p and all its children from the database.
will not remove c from the database; it will ony remove the link to p (and cause a NOT NULL
constraint violation, in this case). You need to explicitly delete() the Child.
Parent p = (Parent) session.load(Parent.class, pid);
Child c = (Child) p.getChildren().iterator().next();
p.getChildren().remove(c);
session.delete(c);
session.flush();
Now, in our case, a Child can't really exist without its parent. So if we remove a Child from the
collection, we really do want it to be deleted. For this, we must use cascade="all-delete-
orphan".
Note: even though the collection mapping specifies inverse="true", cascades are still
processed by iterating the collection elements. So if you require that an object be saved, deleted
or updated by cascade, you must add it to the collection. It is not enough to simply call
setParent().
Prev Up Next
21.2. Bidirectional one-to-many Home 21.4. Cascades and unsaved-value
The following code will update parent and child and insert newChild.
//parent and child were both loaded in a previous session
parent.addChild(child);
Child newChild = new Child();
parent.addChild(newChild);
session.update(parent);
session.flush();
Well, that's all very well for the case of a generated identifier, but what about assigned identifiers
and composite identifiers? This is more difficult, since Hibernate can't use the identifier property
to distinguish between a newly instantiated object (with an identifier assigned by the user) and an
object loaded in a previous session. In this case, Hibernate will either use the timestamp or
version property, or will actually query the second-level cache or, worst case, the database, to see
if the row exists.
Prev Up Next
21.3. Cascading life cycle Home 21.5. Conclusion
21.5. Conclusion
21.5. Conclusion
There is quite a bit to digest here and it might look confusing first time around. However, in
practice, it all works out very nicely. Most Hibernate applications use the parent / child pattern in
many places.
We mentioned an alternative in the first paragraph. None of the above issues exist in the case of
<composite-element> mappings, which have exactly the semantics of a parent / child
relationship. Unfortunately, there are two big limitations to composite element classes:
composite elements may not own collections, and they should not be the child of any entity other
than the unique parent.
Prev Up Next
21.4. Cascades and unsaved-value Chapter 22. Example: Weblog
Home
Application
package eg;
import java.util.List;
import java.text.DateFormat;
import java.util.Calendar;
Prev Next
21.5. Conclusion Home 22.2. Hibernate Mappings
<hibernate-mapping package="eg">
<class
name="Blog"
table="BLOGS">
<id
name="id"
column="BLOG_ID">
<generator class="native"/>
</id>
<property
name="name"
column="NAME"
not-null="true"
unique="true"/>
<bag
name="items"
inverse="true"
order-by="DATE_TIME"
cascade="all">
<key column="BLOG_ID"/>
<one-to-many class="BlogItem"/>
</bag>
</class>
</hibernate-mapping>
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-
3.0.dtd">
<hibernate-mapping package="eg">
<class
name="BlogItem"
table="BLOG_ITEMS"
dynamic-update="true">
<id
name="id"
column="BLOG_ITEM_ID">
<generator class="native"/>
</id>
<property
name="title"
column="TITLE"
not-null="true"/>
<property
name="text"
column="TEXT"
not-null="true"/>
<property
name="datetime"
column="DATE_TIME"
not-null="true"/>
<many-to-one
name="blog"
column="BLOG_ID"
not-null="true"/>
</class>
</hibernate-mapping>
Prev Up Next
Chapter 22. Example: Weblog 22.3. Hibernate Code
Home
Application
22.3. Hibernate Code
Prev Chapter 22. Example: Weblog Application Next
package eg;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Iterator;
import java.util.List;
import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import org.hibernate.tool.hbm2ddl.SchemaExport;
item.setText(text);
result = q.list();
tx.commit();
}
catch (HibernateException he) {
if (tx!=null) tx.rollback();
throw he;
}
finally {
session.close();
}
return result;
}
}
Prev Up Next
22.2. Hibernate Mappings Chapter 23. Example: Various
Home
Mappings
23.1. Employer/Employee
The following model of the relationship between Employer and Employee uses an actual entity
class (Employment) to represent the association. This is done because there might be more than
one period of employment for the same two parties. Components are used to model monetary
values and employee names.
Heres a possible mapping document:
<hibernate-mapping>
<id name="id">
<generator class="sequence">
<param
name="sequence">employment_id_seq</param>
</generator>
</id>
<property name="startDate" column="start_date"/>
<property name="endDate" column="end_date"/>
</class>
</hibernate-mapping>
Prev Next
22.3. Hibernate Code Home 23.2. Author/Work
23.2. Author/Work
Prev Chapter 23. Example: Various Mappings Next
23.2. Author/Work
Consider the following model of the relationships between Work, Author and Person. We
represent the relationship between Work and Author as a many-to-many association. We choose
to represent the relationship between Author and Person as one-to-one association. Another
possibility would be to have Author extend Person.
The following mapping document correctly represents these relationships:
<hibernate-mapping>
<property name="title"/>
<set name="authors" table="author_work">
<key column name="work_id"/>
<many-to-many class="Author" column
name="author_id"/>
</set>
</class>
<property name="alias"/>
<one-to-one name="person" constrained="true"/>
</class>
</hibernate-mapping>
There are four tables in this mapping. works, authors and persons hold work, author and
person data respectively. author_work is an association table linking authors to works. Heres the
table schema, as generated by SchemaExport.
Prev Up Next
Chapter 23. Example: Various 23.3. Customer/Order/Product
Home
Mappings
23.3. Customer/Order/Product
Prev Chapter 23. Example: Various Mappings Next
23.3. Customer/Order/Product
Now consider a model of the relationships between Customer, Order and LineItem and
Product. There is a one-to-many association between Customer and Order, but how should we
represent Order / LineItem / Product? I've chosen to map LineItem as an association class
representing the many-to-many association between Order and Product. In Hibernate, this is
called a composite element.
<hibernate-mapping>
</hibernate-mapping>
customers, orders, line_items and products hold customer, order, order line item and
product data respectively. line_items also acts as an association table linking orders with
products.
Prev Up Next
23.2. Author/Work 23.4. Miscellaneous example
Home
mappings
<id name="customerId"
length="10">
<generator class="assigned"/>
</id>
<list name="orders"
inverse="true"
cascade="save-update">
<key column="customerId"/>
<index column="orderNumber"/>
<one-to-many class="Order"/>
</list>
</class>
<composite-id name="id"
class="Order$Id">
<key-property name="customerId" length="10"/>
<key-property name="orderNumber"/>
</composite-id>
<property name="orderDate"
type="calendar_date"
not-null="true"/>
<property name="total">
<formula>
( select sum(li.quantity*p.price)
from LineItem li, Product p
where li.productId = p.productId
and li.customerId = customerId
and li.orderNumber = orderNumber )
</formula>
</property>
<many-to-one name="customer"
column="customerId"
insert="false"
update="false"
not-null="true"/>
<bag name="lineItems"
fetch="join"
inverse="true"
cascade="save-update">
<key>
<column name="customerId"/>
<column name="orderNumber"/>
</key>
<one-to-many class="LineItem"/>
</bag>
</class>
<class name="LineItem">
<composite-id name="id"
class="LineItem$Id">
<key-property name="customerId" length="10"/>
<key-property name="orderNumber"/>
<key-property name="productId" length="10"/>
</composite-id>
<property name="quantity"/>
<many-to-one name="order"
insert="false"
update="false"
not-null="true">
<column name="customerId"/>
<column name="orderNumber"/>
</many-to-one>
<many-to-one name="product"
insert="false"
update="false"
not-null="true"
column="productId"/>
</class>
<class name="Product">
<synchronize table="LineItem"/>
<id name="productId"
length="10">
<generator class="assigned"/>
</id>
<property name="description"
not-null="true"
length="200"/>
<property name="price" length="3"/>
<property name="numberAvailable"/>
<property name="numberOrdered">
<formula>
( select sum(li.quantity)
from LineItem li
where li.productId = productId )
</formula>
</property>
</class>
<id name="id"
column="person_id"
unsaved-value="0">
<generator class="native"/>
</id>
<discriminator
type="character">
<formula>
case
when title is not null then 'E'
when salesperson is not null then 'C'
else 'P'
end
</formula>
</discriminator>
<property name="name"
not-null="true"
length="80"/>
<property name="sex"
not-null="true"
update="false"/>
<component name="address">
<property name="address"/>
<property name="zip"/>
<property name="country"/>
</component>
<subclass name="Employee"
discriminator-value="E">
<property name="title"
length="20"/>
<property name="salary"/>
<many-to-one name="manager"/>
</subclass>
<subclass name="Customer"
discriminator-value="C">
<property name="comments"/>
<many-to-one name="salesperson"/>
</subclass>
</class>
<id name="id">
<generator class="hilo"/>
</id>
<one-to-one name="address"
property-ref="person"
cascade="all"
fetch="join"/>
<set name="accounts"
inverse="true">
<key column="userId"
property-ref="userId"/>
<one-to-many class="Account"/>
</set>
</class>
<class name="Address">
<id name="id">
<generator class="hilo"/>
</id>
</class>
<class name="Account">
<id name="accountId" length="32">
<generator class="uuid"/>
</id>
<many-to-one name="user"
column="userId"
property-ref="userId"/>
</class>
Prev Up Next
Use an Address class to encapsulate street, suburb, state, postcode. This encourages
code reuse and simplifies refactoring.
Hibernate makes identifier properties optional. There are all sorts of reasons why you
should use them. We recommend that identifiers be 'synthetic' (generated, with no
business meaning).
Identify natural keys for all entities, and map them using <natural-id>. Implement
equals() and hashCode() to compare the properties that make up the natural key.
Don't use a single monolithic mapping document. Map com.eg.Foo in the file
com/eg/Foo.hbm.xml. This makes particularly good sense in a team environment.
As in JDBC, always replace non-constant values by "?". Never use string manipulation to
bind a non-constant value in a query! Even better, consider using named parameters in
queries.
Suppose you have a Java type, say from some library, that needs to be persisted but
doesn't provide the accessors needed to map it as a component. You should consider
implementing org.hibernate.UserType. This approach frees the application code from
implementing transformations to / from a Hibernate type.
In performance-critical areas of the system, some kinds of operations might benefit from
direct JDBC. But please, wait until you know something is a bottleneck. And don't
assume that direct JDBC is necessarily faster. If you need to use direct JDBC, it might be
worth opening a Hibernate Session and using that JDBC connection. That way you can
still use the same transaction strategy and underlying connection provider.
From time to time the Session synchronizes its persistent state with the database.
Performance will be affected if this process occurs too often. You may sometimes
minimize unnecessary flushing by disabling automatic flushing or even by changing the
order of queries and other operations within a particular transaction.
When using a servlet / session bean architecture, you could pass persistent objects loaded
in the session bean to and from the servlet / JSP layer. Use a new session to service each
request. Use Session.merge() or Session.saveOrUpdate() to synchronize objects
with the database.
This is more of a necessary practice than a "best" practice. When an exception occurs,
roll back the Transaction and close the Session. If you don't, Hibernate can't guarantee
that in-memory state accurately represents persistent state. As a special case of this, do
not use Session.load() to determine if an instance with the given identifier exists on
the database; use Session.get() or a query instead.
Use eager fetching sparingly. Use proxies and lazy collections for most associations to
classes that are not likely to be completely held in the second-level cache. For
associations to cached classes, where there is an a extremely high probability of a cache
hit, explicitly disable eager fetching using lazy="false". When an join fetching is
appropriate to a particular use case, use a query with a left join fetch.
Use the open session in view pattern, or a disciplined assembly phase to avoid problems with
unfetched data.
Hibernate frees the developer from writing tedious Data Transfer Objects (DTO). In a
traditional EJB architecture, DTOs serve dual purposes: first, they work around the
problem that entity beans are not serializable; second, they implicitly define an assembly
phase where all data to be used by the view is fetched and marshalled into the DTOs
before returning control to the presentation tier. Hibernate eliminates the first purpose.
However, you will still need an assembly phase (think of your business methods as
having a strict contract with the presentation tier about what data is available in the
detached objects) unless you are prepared to hold the persistence context (the session)
open across the view rendering process. This is not a limitation of Hibernate! It is a
fundamental requirement of safe transactional data access.
Hide (Hibernate) data-access code behind an interface. Combine the DAO and Thread
Local Session patterns. You can even have some classes persisted by handcoded JDBC,
associated to Hibernate via a UserType. (This advice is intended for "sufficiently large"
applications; it is not appropriate for an application with five tables!)
Good usecases for a real many-to-many associations are rare. Most of the time you need
additional information stored in the "link table". In this case, it is much better to use two
one-to-many associations to an intermediate link class. In fact, we think that most
associations are one-to-many and many-to-one, you should be careful when using any
other association style and ask yourself if it is really neccessary.
11
Ho
me
Ins
ur
an
ce
80
0
20
05
-
02
-
02
00
:0
0:
00
12
Ho
me
Ins
ur
an
ce
75
0
20
04
-
09
-
09
00
:0
0:
00
13
M
ot
Hibernate Select Clause
In this lesson we will write example code to select the data from Insurance table using Hibernate
Select Clause. The select clause picks up objects and properties to return in the query result set.
Here is the query:
Hibernate generates the necessary sql query and selects all the records from Insurance table.
Here is the code of our java file which shows how select HQL can be used:
package roseindia.tutorial.hibernate;
import org.hibernate.Session;
import org.hibernate.*;
import org.hibernate.cfg.*;
import java.util.*;
/**
* @author Deepak Kumar
*
* http://www.roseindia.net
* HQL Select Clause Example
*/
public class SelectClauseExample {
public static void main(String[] args) {
Session session = null;
try{
// This step will read hibernate.cfg.xml
and prepare hibernate for use
SessionFactory sessionFactory = new
Configuration().configure()
.buildSessionFactory();
session =sessionFactory.openSession();
lngInsuranceId,insurance.insuranceName," +
"insurance.investementAmount,insurance.
session.close();
}catch(Exception e){
System.out.println(e.getMessage());
}finally{
}
}
}
To run the example select Run-> Run As -> Java Application from the menu bar. Following out
is displayed in the Eclipse console:
ID: 1
Amount: 1000
ID: 2
ID: 3
Amount: 500
ID: 4
Amount: 2500
ID: 5
Amount: 500
ID: 6
Amount: 900
ID: 7
Amount: 2000
ID: 8
Amount: 600
ID: 9
Amount: 700
ID: 10
ID: 11
Amount: 800
ID: 12
Amount: 750
ID: 13
Amount: 900
ID: 14
Amount: 780
In this example you will learn how to use the HQL from clause. The from clause is the simplest
possible Hibernate Query. Example of from clause is:
import org.hibernate.Session;
import org.hibernate.*;
import org.hibernate.cfg.*;
import java.util.*;
/**
* @author Deepak Kumar
*
* http://www.roseindia.net
* Select HQL Example
*/
public class SelectHQLExample {
try{
// This step will read hibernate.cfg.xml
and prepare hibernate for use
SessionFactory sessionFactory = new
Configuration().configure().buildSessionFactory();
session =sessionFactory.openSession();
session.close();
}catch(Exception e){
System.out.println(e.getMessage());
}finally{
}
}
}
To run the example select Run-> Run As -> Java Application from the menu bar. Following out
is displayed in the Eclipse console:
ID: 1
ID: 2
ID: 3
ID: 4
ID: 5
ID: 6
ID: 7
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. For example:
Where Clause can be used with or without Select Clause. Here the example code:
package roseindia.tutorial.hibernate;
import org.hibernate.Session;
import org.hibernate.*;
import org.hibernate.cfg.*;
import java.util.*;
/**
* @author Deepak Kumar
*
* http://www.roseindia.net
* HQL Where Clause Example
* Where Clause With Select Clause Example
*/
public class WhereClauseExample {
public static void main(String[] args) {
Session session = null;
try{
// This step will read hibernate.cfg.
xml and prepare hibernate for use
SessionFactory sessionFactory = new
Configuration().configure().
buildSessionFactory();
session =sessionFactory.openSession();
System.out.println("***************
****************");
System.out.println("Query using
Hibernate Query Language");
//Query using Hibernate Query Language
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());
}
System.out.println("****************
***************");
System.out.println("Where Clause With
Select Clause");
//Where Clause With Select Clause
SQL_QUERY ="Select insurance.
lngInsuranceId,insurance.insuranceName," +
"insurance.investementAmount,
insurance.investementDate from Insurance
insurance "+ " where insurance.
lngInsuranceId='1'";
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("***************
****************");
session.close();
}catch(Exception e){
System.out.println(e.getMessage());
}finally{
}
}
}
To run the example select Run-> Run As -> Java Application from the menu bar. Following out
is displayed in the Eclipse console:
*******************************
ID: 1
*******************************
Where Clause With Select Clause
ID: 1
*******************************
Order by clause is used to retrieve the data from database in the sorted order by any property of
returned class or components. HQL supports Order By Clause. In our example we will retrieve
the data sorted on the insurance type. Here is the java example code:
package roseindia.tutorial.hibernate;
import org.hibernate.Session;
import org.hibernate.*;
import org.hibernate.cfg.*;
import java.util.*;
/**
* @author Deepak Kumar
*
* http://www.roseindia.net HQL Order by Clause Example
*
*/
public class HQLOrderByExample {
public static void main(String[] args) {
Session session = null;
try {
// This step will read hibernate.
cfg.xml and prepare hibernate for
// use
SessionFactory sessionFactory =
new Configuration().configure()
.buildSessionFactory();
session = sessionFactory.openSession();
//Order By Example
String SQL_QUERY = " from Insurance as
insurance order by insurance.insuranceName";
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());
}
session.close();
} catch (Exception e) {
System.out.println(e.getMessage());
} finally {
}
}
}
To run the example select Run-> Run As -> Java Application from the menu bar. Following out
is displayed in the Eclipse console:
ID: 1
ID: 4
ID: 5
ID: 11
ID: 12
ID: 2
ID: 3
ID: 6
ID: 9
ID: 10
ID: 13
ID: 14
ID: 7
ID: 8
Group by clause is used to return the aggregate values by grouping on returned component. HQL
supports Group By Clause. In our example we will calculate the sum of invested amount in each
insurance type. Here is the java code for calculating the invested amount insurance wise:
package roseindia.tutorial.hibernate;
import org.hibernate.Session;
import org.hibernate.*;
import org.hibernate.cfg.*;
import java.util.*;
/**
* @author Deepak Kumar
*
* http://www.roseindia.net
HQL Group by Clause Example
*
*/
public class HQLGroupByExample {
public static void main(String[] args) {
Session session = null;
try {
// This step will read
hibernate.cfg.xml and prepare hibernate for
// use
SessionFactory sessionFactory =
new Configuration().configure()
.buildSessionFactory();
session = sessionFactory.openSession();
//Group By Clause Example
String SQL_QUERY = "select sum
(insurance.investementAmount),
insurance.insuranceName "
+ "from Insurance insurance
group by insurance.insuranceName";
Query query = session.createQuery(SQL_QUERY);
for (Iterator it =
query.iterate(); it.hasNext();) {
Object[] row = (Object[]) it.next();
System.out.println("
Invested Amount: " + row[0]);
System.out.println("
Insurance Name: " + row[1]);
}
session.close();
} catch (Exception e) {
System.out.println(e.getMessage());
} finally {
}
}
}
To run the example select Run-> Run As -> Java Application from the menu bar. Following out
is displayed in the Eclipse console:
Order by clause is used to retrieve the data from database in the sorted order by any property of
returned class or components. HQL supports Order By Clause. In our example we will retrieve
the data sorted on the insurance type. Here is the java example code:
package roseindia.tutorial.hibernate;
import org.hibernate.Session;
import org.hibernate.*;
import org.hibernate.cfg.*;
import java.util.*;
/**
* @author Deepak Kumar
*
* http://www.roseindia.net HQL Order by Clause Example
*
*/
public class HQLOrderByExample {
public static void main(String[] args) {
Session session = null;
try {
// This step will read hibernate.
cfg.xml and prepare hibernate for
// use
SessionFactory sessionFactory =
new Configuration().configure()
.buildSessionFactory();
session = sessionFactory.openSession();
//Order By Example
String SQL_QUERY = " from Insurance as
insurance order by insurance.insuranceName";
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());
}
session.close();
} catch (Exception e) {
System.out.println(e.getMessage());
} finally {
}
}
}
To run the example select Run-> Run As -> Java Application from the menu bar. Following out
is displayed in the Eclipse console:
ID: 1
ID: 4
ID: 5
ID: 11
ID: 12
ID: 2
ID: 3
ID: 6
ID: 9
ID: 10
ID: 13
ID: 14
ID: 7
ID: 8