Добавил:
Upload Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
lect17-hibernate-orm / more / hibernate_reference.pdf
Скачиваний:
90
Добавлен:
18.03.2015
Размер:
2.2 Mб
Скачать

Chapter 11. Working with objects

public class MyDao {

doStuff() {

Query q = s.getNamedQuery("night.moreRecentThan");

q.setDate( "date", aMonthAgo );

List results = q.list();

...

}

...

}

Using a mapping document can be configured using the <query> node. Remember to use a CDATA section if your query contains characters that could be interpreted as markup.

Example 11.2. Defining a named query using <query>

<query name="ByNameAndMaximumWeight"><![CDATA[ from eg.DomesticCat as cat

where cat.name = ? and cat.weight > ?

] ]></query>

Parameter binding and executing is done programatically as seen in Example 11.3, “Parameter binding of a named query”.

Example 11.3. Parameter binding of a named query

Query q = sess.getNamedQuery("ByNameAndMaximumWeight");

q.setString(0, name);

q.setInt(1, minWeight);

List cats = q.list();

The actual program code is independent of the query language that is used. You can also define native SQL queries in metadata, or migrate existing queries to Hibernate by placing them in mapping files.

Also note that a query declaration inside a <hibernate-mapping> element requires a global unique name for the query, while a query declaration inside a <class> element is made unique automatically by prepending the fully qualified name of the class. For example eg.Cat.ByNameAndMaximumWeight.

11.4.2. Filtering collections

A collection filter is a special type of query that can be applied to a persistent collection or array. The query string can refer to this, meaning the current collection element.

Collection blackKittens = session.createFilter(

220

Criteria queries

pk.getKittens(),

"where this.color = ?")

.setParameter( Color.BLACK, Hibernate.custom(ColorUserType.class) )

.list()

);

The returned collection is considered a bag that is a copy of the given collection. The original collection is not modified. This is contrary to the implication of the name "filter", but consistent with expected behavior.

Observe that filters do not require a from clause, although they can have one if required. Filters are not limited to returning the collection elements themselves.

Collection blackKittenMates = session.createFilter(

pk.getKittens(),

"select this.mate where this.color = eg.Color.BLACK.intValue")

.list();

Even an empty filter query is useful, e.g. to load a subset of elements in a large collection:

Collection tenKittens = session.createFilter(

mother.getKittens(), "")

.setFirstResult(0).setMaxResults(10)

.list();

11.4.3. Criteria queries

HQL is extremely powerful, but some developers prefer to build queries dynamically using an object-oriented API, rather than building query strings. Hibernate provides an intuitive Criteria query API for these cases:

Criteria crit = session.createCriteria(Cat.class);

crit.add( Restrictions.eq( "color", eg.Color.BLACK ) );

crit.setMaxResults(10);

List cats = crit.list();

The Criteria and the associated Example API are discussed in more detail in Chapter 17, Criteria

Queries.

11.4.4. Queries in native SQL

You can express a query in SQL, using createSQLQuery() and let Hibernate manage the mapping from result sets to objects. You can at any time call session.connection() and use the JDBC Connection directly. If you choose to use the Hibernate API, you must enclose SQL aliases in braces:

221

Соседние файлы в папке more