ThinkSSL🔒 一键申购 5分钟快速签发 30天无理由退款 购买更放心 广告
# 7.6\. 更复杂的关联映射 更复杂的关联连接_极为_罕见。 通过在映射文档中嵌入SQL片断,Hibernate也可以处理更为复杂的情况。比如,假若包含历史帐户数据的表定义了`accountNumber`, `effectiveEndDate` 和`effectiveStartDate`字段,按照下面映射: ``` <properties name="currentAccountKey"> <property name="accountNumber" type="string" not-null="true"/> <property name="currentAccount" type="boolean"> <formula>case when effectiveEndDate is null then 1 else 0 end</formula> </property> </properties> <property name="effectiveEndDate" type="date"/> <property name="effectiveStateDate" type="date" not-null="true"/> ``` 那么我们可以对_目前(current)_实例(其`effectiveEndDate`为null)使用这样的关联映射: ``` <many-to-one name="currentAccountInfo" property-ref="currentAccountKey" class="AccountInfo"> <column name="accountNumber"/> <formula>'1'</formula> </many-to-one> ``` 更复杂的例子,假想`Employee`和`Organization`之间的关联是通过一个`Employment`中间表维护的,而中间表中填充了很多历史雇员数据。那“雇员的_最新_雇主”这个关联(最新雇主就是`startDate`最后的那个)可以这样映射: ``` <join> <key column="employeeId"/> <subselect> select employeeId, orgId from Employments group by orgId having startDate = max(startDate) </subselect> <many-to-one name="mostRecentEmployer" class="Organization" column="orgId"/> </join> ``` 使用这一功能时可以充满创意,但通常更加实用的是用HQL或条件查询来处理这些情形。