Java Reference
In-Depth Information
simple HQL named query, and one simple SQL query that does the same thing, we have the
Hibernate mapping file shown in Listing 9-4: Product.hbm.xml .
Listing 9-4. Product.hbm.xml
<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-mapping
PUBLIC "-//Hibernate/Hibernate Mapping DTD//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping package="com.hibernatebook.criteria">
<class name="Product">
<id name="id" type="int">
<generator class="native"/>
</id>
<property name="name" type="string"/>
<property name="description" type="string"/>
<property name="price" type="double"/>
<many-to-one name="supplier" class="Supplier" column="supplierId"/>
</class>
<query name="com.hibernatebook.criteria.Product.HQLpricing"><![CDATA[
select product.price from Product product where product.price > 25.0]]>
</query>
<sql-query name="com.hibernatebook.criteria.Product.SQLpricing">
<return-scalar column="price" type="double"/>
<![CDATA[
select product.price from Product as product where product.price > 25.0]]>
</sql-query>
</hibernate-mapping>
Notice that we embedded the SQL and HQL queries in CDATA regions. This protects our
SQL queries from interfering with the XML parser—we don't have to worry about special char-
acters breaking the XML. For the native SQL query, we also had to specify a return type, so
Hibernate knows what type of result data to expect from the database. When you use HQL,
Hibernate handles that mapping behind the scenes, because it knows which objects went in.
With SQL, you have to specify the return types yourself. In this case, we used the <return-scalar>
XML element to define our return type as a column named price , with a type of double . Hiber-
nate converts the JDBC result set into an array of objects, just like the previous HQL query.
Functionally, they are identical. We discuss native SQL in more detail in the next section of
the chapter.
You may also specify the flush mode, whether the query is cacheable, the cache region,
the fetch size, and the timeout for the HQL and SQL queries. For the SQL query, you may addi-
tionally specify whether the SQL query is callable.
Search WWH ::




Custom Search