|
Hibernate example source code file (query_criteria.xml)
This example Hibernate source code file (query_criteria.xml) is included in the DevDaily.com
"Java Source Code
Warehouse" project. The intent of this project is to help you "Learn Java by Example" TM.
The Hibernate query_criteria.xml source code
<?xml version='1.0' encoding="UTF-8"?>
<!--
~ Hibernate, Relational Persistence for Idiomatic Java
~
~ Copyright (c) 2008, Red Hat Middleware LLC or third-party contributors as
~ indicated by the @author tags or express copyright attribution
~ statements applied by the authors. All third-party contributions are
~ distributed under license by Red Hat Middleware LLC.
~
~ This copyrighted material is made available to anyone wishing to use, modify,
~ copy, or redistribute it subject to the terms and conditions of the GNU
~ Lesser General Public License, as published by the Free Software Foundation.
~
~ This program is distributed in the hope that it will be useful,
~ but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
~ or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License
~ for more details.
~
~ You should have received a copy of the GNU Lesser General Public License
~ along with this distribution; if not, write to:
~ Free Software Foundation, Inc.
~ 51 Franklin Street, Fifth Floor
~ Boston, MA 02110-1301 USA
-->
<!DOCTYPE chapter PUBLIC "-//OASIS//DTD DocBook XML V4.5//EN" "http://www.oasis-open.org/docbook/xml/4.5/docbookx.dtd" [
<!ENTITY % BOOK_ENTITIES SYSTEM "../HIBERNATE_-_Relational_Persistence_for_Idiomatic_Java.ent">
%BOOK_ENTITIES;
]>
<chapter id="querycriteria">
<title>Criteria Queries
<para>
Hibernate features an intuitive, extensible criteria query API.
</para>
<section id="querycriteria-creating">
<title>Creating a Criteria instance
<para>
The interface <literal>org.hibernate.Criteria represents a query against
a particular persistent class. The <literal>Session is a factory for
<literal>Criteria instances.
</para>
<programlisting role="JAVA">
</section>
<section id="querycriteria-narrowing">
<title>Narrowing the result set
<para>
An individual query criterion is an instance of the interface
<literal>org.hibernate.criterion.Criterion. The class
<literal>org.hibernate.criterion.Restrictions defines
factory methods for obtaining certain built-in
<literal>Criterion types.
</para>
<programlisting role="JAVA">
<para>
Restrictions can be grouped logically.
</para>
<programlisting role="JAVA">
<programlisting role="JAVA">
<para>
There are a range of built-in criterion types (<literal>Restrictions
subclasses). One of the most useful allows you to specify SQL directly.
</para>
<programlisting role="JAVA">
<para>
The <literal>{alias} placeholder with be replaced by the row alias
of the queried entity.
</para>
<para>
You can also obtain a criterion from a
<literal>Property instance. You can create a Property
by calling <literal>Property.forName():
</para>
<programlisting role="JAVA">
</section>
<section id="querycriteria-ordering">
<title>Ordering the results
<para>
You can order the results using <literal>org.hibernate.criterion.Order.
</para>
<programlisting role="JAVA">
<programlisting role="JAVA">
</section>
<section id="querycriteria-associations" revision="2">
<title>Associations
<para>
By navigating
associations using <literal>createCriteria() you can specify constraints upon related entities:
</para>
<programlisting role="JAVA">
<para>
The second <literal>createCriteria() returns a new
instance of <literal>Criteria that refers to the elements of
the <literal>kittens collection.
</para>
<para>
There is also an alternate form that is useful in certain circumstances:
</para>
<programlisting role="JAVA">
<para>
(<literal>createAlias() does not create a new instance of
<literal>Criteria.)
</para>
<para>
The kittens collections held by the <literal>Cat instances
returned by the previous two queries are <emphasis>not pre-filtered
by the criteria. If you want to retrieve just the kittens that match the
criteria, you must use a <literal>ResultTransformer.
</para>
<programlisting role="JAVA">
<para>
Additionally you may manipulate the result set using a left outer join:
</para>
<programlisting>
<para>
This will return all of the <literal>Cats with a mate whose name starts with "good"
ordered by their mate's age, and all cats who do not have a mate.
This is useful when there is a need to order or limit in the database
prior to returning complex/large result sets, and removes many instances where
multiple queries would have to be performed and the results unioned
by java in memory.
</para>
<para>
Without this feature, first all of the cats without a mate would need to be loaded in one query.
</para>
<para>
A second query would need to retreive the cats with mates who's name started with "good" sorted by the mates age.
</para>
<para>
Thirdly, in memory; the lists would need to be joined manually.
</para>
</section>
<section id="querycriteria-dynamicfetching" revision="1">
<title>Dynamic association fetching
<para>
You can specify association fetching semantics at runtime using
<literal>setFetchMode().
</para>
<programlisting role="JAVA">
<para>
This query will fetch both <literal>mate and kittens
by outer join. See <xref linkend="performance-fetching"/> for more information.
</para>
</section>
<section id="querycriteria-components" revision="2">
<title>Components
<para>
To add a restriction against a property of an embedded component, the component property
name should be prepended to the property name when creating the <literal>Restriction.
The criteria object should be created on the owning entity, and cannot be created on the component
itself. For example, suppose the <literal>Cat has a component property fullName
with sub-properties <literal>firstName and lastName:
</para>
<programlisting>
<para>
When using criteria against collections, there are two distinct cases. One is if
the collection contains entities (eg. <literal><one-to-many/>
or <literal><many-to-many/>) or components
(<literal><composite-element/> ),
and the second is if the collection contains scalar values
(<literal><element/>).
In the first case, the syntax is as given above in the section
<xref linkend="querycriteria-associations"/> where we restrict the kittens
collection. Essentially we create a <literal>Criteria object against the collection
property and restrict the entity or component properties using that instance.
</para>
<para>
For queryng a collection of basic values, we still create the <literal>Criteria
object against the collection, but to reference the value, we use the special property
"elements". For an indexed collection, we can also reference the index property using
the special property "indices".
</para>
<programlisting>
<para>
The class <literal>org.hibernate.criterion.Example allows
you to construct a query criterion from a given instance.
</para>
<programlisting role="JAVA">
<para>
Version properties, identifiers and associations are ignored. By default,
null valued properties are excluded.
</para>
<para>
You can adjust how the <literal>Example is applied.
</para>
<programlisting role="JAVA">
<para>
You can even use examples to place criteria upon associated objects.
</para>
<programlisting role="JAVA">
</section>
<section id="querycriteria-projection">
<title>Projections, aggregation and grouping
<para>
The class <literal>org.hibernate.criterion.Projections is a
factory for <literal>Projection instances. You can apply a
projection to a query by calling <literal>setProjection().
</para>
<programlisting role="JAVA">
<programlisting role="JAVA">
<para>
There is no explicit "group by" necessary in a criteria query. Certain
projection types are defined to be <emphasis>grouping projections,
which also appear in the SQL <literal>group by clause.
</para>
<para>
An alias can be assigned to a projection so that the projected value
can be referred to in restrictions or orderings. Here are two different ways to
do this:
</para>
<programlisting role="JAVA">
<programlisting role="JAVA">
<para>
The <literal>alias() and as() methods simply wrap a
projection instance in another, aliased, instance of <literal>Projection.
As a shortcut, you can assign an alias when you add the projection to a
projection list:
</para>
<programlisting role="JAVA">
<programlisting role="JAVA">
<para>
You can also use <literal>Property.forName() to express projections:
</para>
<programlisting role="JAVA">
<programlisting role="JAVA">
</section>
<section id="querycriteria-detachedqueries">
<title>Detached queries and subqueries
<para>
The <literal>DetachedCriteria class allows you to create a query outside the scope
of a session and then execute it using an arbitrary <literal>Session.
</para>
<programlisting role="JAVA">
<para>
A <literal>DetachedCriteria can also be used to express a subquery. Criterion
instances involving subqueries can be obtained via <literal>Subqueries or
<literal>Property.
</para>
<programlisting role="JAVA">
<programlisting role="JAVA">
<para>
Correlated subqueries are also possible:
</para>
<programlisting role="JAVA">
</section>
<!--TODO: ResultSetTransformer + aliasing. AliasToBeanTransformer allow returning arbitrary
user objects - similar to setResultClass in JDO2. General use of ResultTransformer
could also be explained. -->
<section id="query-criteria-naturalid">
<title>Queries by natural identifier
<para>
For most queries, including criteria queries, the query cache is not efficient
because query cache invalidation occurs too frequently. However, there is a special
kind of query where you can optimize the cache invalidation algorithm: lookups by a
constant natural key. In some applications, this kind of query occurs frequently.
The criteria API provides special provision for this use case.
</para>
<para>
First, map the natural key of your entity using
<literal><natural-id> and enable use of the second-level cache.
</para>
<programlisting role="XML">
<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>]]>
<para>
This functionality is not intended for use with entities with
<emphasis>mutable natural keys.
</para>
<para>
Once you have enabled the Hibernate query cache,
the <literal>Restrictions.naturalId() allows you to make use of
the more efficient cache algorithm.
</para>
<programlisting role="JAVA">
</section>
</chapter>
Other Hibernate examples (source code examples)
Here is a short list of links related to this Hibernate query_criteria.xml source code file:
|