16.4. 定制装载SQL

你可能需要声明你自己的SQL(或HQL)来装载实体

  1. <sql-query name="person">
  2. <return alias="pers" class="Person" lock-mode="upgrade"/>
  3. SELECT NAME AS {pers.name}, ID AS {pers.id}
  4. FROM PERSON
  5. WHERE ID=?
  6. FOR UPDATE
  7. </sql-query>

这只是一个前面讨论过的命名查询声明,你可以在类映射里引用这个命名查询。

  1. <class name="Person">
  2. <id name="id">
  3. <generator class="increment"/>
  4. </id>
  5. <property name="name" not-null="true"/>
  6. <loader query-ref="person"/>
  7. </class>

这也可以用于存储过程

你甚至可以定一个用于集合装载的查询:

  1. <set name="employments" inverse="true">
  2. <key/>
  3. <one-to-many class="Employment"/>
  4. <loader query-ref="employments"/>
  5. </set>
  1. <sql-query name="employments">
  2. <load-collection alias="emp" role="Person.employments"/>
  3. SELECT {emp.*}
  4. FROM EMPLOYMENT emp
  5. WHERE EMPLOYER = :id
  6. ORDER BY STARTDATE ASC, EMPLOYEE ASC
  7. </sql-query>

你甚至还可以定义一个实体装载器,它通过连接抓取装载一个集合:

  1. <sql-query name="person">
  2. <return alias="pers" class="Person"/>
  3. <return-join alias="emp" property="pers.employments"/>
  4. SELECT NAME AS {pers.*}, {emp.*}
  5. FROM PERSON pers
  6. LEFT OUTER JOIN EMPLOYMENT emp
  7. ON pers.ID = emp.PERSON_ID
  8. WHERE ID=?
  9. </sql-query>