命名查询。这个查询在任何时候当我们使用get(),load()装载person或使用惰性关联获取数据时都会执行它。一般来讲,这个命名查询应该是一个SQL语句,如下面如示:
<sql-query name="person">
<return alias="p" class="Person" lock-mode="upgrade"/>
SELECT NAME AS {p.name}, ID AS {p.id} FROM PERSON WHERE ID=? FOR UPDATE
</sql-query>
注:一个本地的SQL查询可能会返回多个"实体列",但本例比较简单,只返回了一个实体。
Employment相对更复杂一点,而且并不是所有的属性都包括在INSERT和UPDATE中。定义如下:
<class name="Employment" lazy="true">
<id name="id" unsaved-value="0">
<generator class="increment"/>
</id>
<many-to-one name="employee" not-null="true" update="false"/>
<many-to-one name="employer" not-null="true" update="false"/>
<property name="startDate" not-null="true" update="false"
insert="false"/>
<property name="endDate" insert="false"/>
<property name="regionCode" update="false"/>
<loader query-ref="employment"/>
<sql-insert>
INSERT INTO EMPLOYMENT
(EMPLOYEE, EMPLOYER, STARTDATE, REGIONCODE, ID)
VALUES (?, ?, CURRENT_DATE, UPPER(?), ?)
</sql-insert>
<sql-update>UPDATE EMPLOYMENT SET ENDDATE=? WHERE ID=?</sql-update>
<sql-delete>DELETE FROM EMPLOYMENT WHERE ID=?</sql-delete>
</class>
Hibernate3.x:最出色的ORM框架(2)
时间:2011-03-07 IT168 极地圣火
下面是命名查询employment的定义:
<sql-query name="employment">
<return alias="emp" class="Employment"/>
SELECT EMPLOYEE AS {emp.employee}, EMPLOYER AS {emp.employer},
STARTDATE AS {emp.startDate}, ENDDATE AS {emp.endDate},
REGIONCODE as {emp.regionCode}, ID AS {emp.id}
FROM EMPLOYMENT
WHERE ID = ?
</sql-query>
下面的Organization的定义:
<class name="Organization" lazy="true">
<id name="id" unsaved-value="0">
<generator class="increment"/>
</id>
<property name="name" not-null="true"/>
<set name="employments"
lazy="true"
inverse="true">
<key column="employer"/>
<one-to-many class="Employment"/>
<loader query-ref="organizationEmployments"/>
</set>
<loader query-ref="organization"/>
<sql-insert>
INSERT INTO ORGANIZATION (NAME, ID) VALUES ( UPPER(?), ? )
</sql-insert>
<sql-update>UPDATE ORGANIZATION SET NAME=UPPER(?) WHERE ID=?</sql-update>
<sql-delete>DELETE FROM ORGANIZATION WHERE ID=?</sql-delete>
</class>
下面是两个命名查询的定义:
<sql-query name="organization">
<return alias="org" class="Organization"/>
SELECT NAME A
|