日期:2014-05-16  浏览次数:20476 次

ibaties 中一对多映射关联查询

由于使用ibaties不像hibanate 中那么方便使用关联查询,不过,ibatis中变通一下也是可以实现这种关联一对多查询,直接进入例子:

业务场景如下:

要查询一个疾病的信息,但是这个疾病信息中需要查出这个疾病所关联的科室,而且一个疾病会关联多个科室。

库表设计如下:

疾病表:disease

id

name

intorduct

疾病科室关系表: disease_department_relation

id

diseaseid

departmentid

科室表

departmentid

departmentname

 

java中存放疾病信息的对象如下:

public class Disease{

private String id;

private String name;

private String introduction;

private List<Department> department;

}

public clas Department{

private String departmentid;

private String departmentname;

}

ibaties中的查询sql如下:

<resultMap class="Department" id="departmentResult">
  <result property="departmentId" column="departmentid"/>
  <result property="departmentName" column="departmentname"/>
 </resultMap>

<resultMap id="diseaseResult" class="Disease">

<result property="id" column="diseaseid" />
 <result property="name" column="diseasename" />

<result property="introduction" column="introduction" />

<result property="departmentDo" column="{diseaseid=diseaseid}"
   select="query_disease_by_diseaseid"/>

</resultMap>

 

<select id="query_disease_by_id" resultMap="diseaseResult">

select diseaseid id ,diseasename name,intorduction  from disease where diseaseid=#diseaseid#

</select>

<select id="query_disease_by_diseaseid" resultMap="departmentResult">

select d.departmentid, d.departmentname from disease_department_relation ddr ,department d where

ddr.departmentid=d.departmentid and diseaseid=#diseaseid#

</select>

注:departmentResult 中cloumn="{diseaseid=diseaseid}" 这个说明下

这个{}中可以写多个这种属性,看项目需要,由于我的disease表跟disease_department_relation 关联是通过diseaseid进行关联的,这里我只需要传递一个diseaseid过去,所以等号前面的diseaseid是我的这个变量名 等号后面的是我的表disease中的column disease 的值。