16.2. 命名SQL查询

可以在映射文档中定义查询的名字,然后就可以象调用一个命名的HQL查询一样直接调用命名SQL查询.在这种情况下,我们 需要调用addEntity()方法.

  1. <sql-query name="persons">
  2. <return alias="person" class="eg.Person"/>
  3. SELECT person.NAME AS {person.name},
  4. person.AGE AS {person.age},
  5. person.SEX AS {person.sex}
  6. FROM PERSON person
  7. WHERE person.NAME LIKE :namePattern
  8. </sql-query>
  1. List people = sess.getNamedQuery("persons")
  2. .setString("namePattern", namePattern)
  3. .setMaxResults(50)
  4. .list();

&lt;return-join&gt;&lt;load-collection&gt; 元素是用来连接关联以及将查询定义为预先初始化各个集合的。

  1. <sql-query name="personsWith">
  2. <return alias="person" class="eg.Person"/>
  3. <return-join alias="address" property="person.mailingAddress"/>
  4. SELECT person.NAME AS {person.name},
  5. person.AGE AS {person.age},
  6. person.SEX AS {person.sex},
  7. adddress.STREET AS {address.street},
  8. adddress.CITY AS {address.city},
  9. adddress.STATE AS {address.state},
  10. adddress.ZIP AS {address.zip}
  11. FROM PERSON person
  12. JOIN ADDRESS adddress
  13. ON person.ID = address.PERSON_ID AND address.TYPE='MAILING'
  14. WHERE person.NAME LIKE :namePattern
  15. </sql-query>

一个命名查询可能会返回一个标量值.你必须使用&lt;return-scalar&gt;元素来指定字段的别名和 Hibernate类型

  1. <sql-query name="mySqlQuery">
  2. <return-scalar column="name" type="string"/>
  3. <return-scalar column="age" type="long"/>
  4. SELECT p.NAME AS name,
  5. p.AGE AS age,
  6. FROM PERSON p WHERE p.NAME LIKE 'Hiber%'
  7. </sql-query>

你可以把结果集映射的信息放在外部的&lt;resultset&gt;元素中,这样就可以在多个命名查询间,或者通过setResultSetMapping()API来访问。(此处原文即存疑。原文为:You can externalize the resultset mapping informations in a &lt;resultset&gt; element to either reuse them accross several named queries or through the setResultSetMapping() API.)

  1. <resultset name="personAddress">
  2. <return alias="person" class="eg.Person"/>
  3. <return-join alias="address" property="person.mailingAddress"/>
  4. </resultset>
  5. <sql-query name="personsWith" resultset-ref="personAddress">
  6. SELECT person.NAME AS {person.name},
  7. person.AGE AS {person.age},
  8. person.SEX AS {person.sex},
  9. adddress.STREET AS {address.street},
  10. adddress.CITY AS {address.city},
  11. adddress.STATE AS {address.state},
  12. adddress.ZIP AS {address.zip}
  13. FROM PERSON person
  14. JOIN ADDRESS adddress
  15. ON person.ID = address.PERSON_ID AND address.TYPE='MAILING'
  16. WHERE person.NAME LIKE :namePattern
  17. </sql-query>

另外,你可以在java代码中直接使用hbm文件中的结果集定义信息。

  1. List cats = sess.createSQLQuery(
  2. "select {cat.*}, {kitten.*} from cats cat, cats kitten where kitten.mother = cat.id"
  3. )
  4. .setResultSetMapping("catAndKitten")
  5. .list();