<association>用于两张一对一对应的表的查询,是<resultMap>的子标签。
即A表与B表对应为“一夫一妻”,而不是”一夫多妻“或”多夫多妻“的关联关系
表的字段
A表:D1,D2,D3,D4,D5
B表:D6,D7
类的属性
ccc1类:DD1,DD2,DD3,D4,CCC2
ccc2类:DD6,DD7
<association>两次查询的方法
关键代码
<resultMap id="findC" type="ccc1">
<id column="D1" property="DD1"/>
<result column="D2" property="DD2"/>
<result column="D3" property="DD3"/>
<result column="D4" property="DD4"/>
<association column="D1" javaType="ccc2" property="card"
select="com.xxx.xxx.ccc2Mapper.findB"/>
</resultMap>
<select id="findA" parameterType="Integer" resultMap="findC">
select * from xxx where D1=#{D1}
</select>
运行过程:
1,首先执行 findA的SQL: select * from xxx where D1=#{D1} 获取结果
2,再通过<resultMap>里的<id><result>(二者是同样的效果)把结果分给java类ccc1对应的属性。即D1字段对应DD1属性。
3,再 执 行 findB的SQL: select="com.xxx.xxx.ccc2Mapper.findB" 获取结果。笔者这里没有给出findB的SQL语句内容。
4,执行finB获取的结果直接给ccc1类中的ccc2类型的属性CCC2
5,执行完毕
A表:D1,D2,D3,D4,D5。
B表:D6,D7
ccc1类:DD1,DD2,DD3,D4,CCC2
ccc2类:DD6,DD7
这里 <association column="D1" 中D1指的是A表中的字段,用作关联B表的依据,传值给findB用于findB的SQL语句的执行参数。
<association>一次查询的方法
关键代码
<resultMap id="findC" type="ccc1">
<id column="D1" property="DD1"/>
<result column="D2" property="DD2"/>
<result column="D3" property="DD3"/>
<result column="D4" property="DD4"/>
<association javaType="ccc2" property="card">
<id column="D6" property="DD6" />
<result column="D7" property="DD7"/>
</association>
</resultMap>
<select id="findA" parameterType="Integer"
resultMap="findC">
select A.*,B.* from A,B where A.D1 = B.D6
and A.D1 = #{D1}
</select>
ccc1类:DD1,DD2,DD3,D4,CCC2
ccc2类:DD6,DD7
运行过程:
1,首先执行findA: select A.*,B.* from A,B where A.D1 = B.D6 and A.D1 = #{D1}
2,再通过<resultMap>里的<id><result>(二者是同样的效果)把结果分给java类ccc1对应的属性。即D1字段对应DD1属性。
3,之后通过 <association>对D6、D7字段分给CCC2。即D7字段对应ccc1类中的ccc2类型的属性CCC2的属性DD7。D6对应DD6。
. 4,执行完毕
一般建议使用一次查询的方法,且这种方法不用写findB方法。
完整例子
<?xml version="1.0" encoding="UTF8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.xxx.xxx.ccc1Mapper">
<resultMap id="findC" type="ccc1">
<id column="D1" property="DD1"/>
<result column="D2" property="DD2"/>
<result column="D3" property="DD3"/>
<result column="D4" property="DD4"/>
<association column="D1" javaType="ccc2" property="card"
select="com.xxx.xxx.ccc2Mapper.findB"/>
</resultMap>
<select id="findA" parameterType="Integer" resultMap="findC">
select * from xxx where D1=#{D1}
</select>
<resultMap id="findC" type="ccc1">
<id column="D1" property="DD1"/>
<result column="D2" property="DD2"/>
<result column="D3" property="DD3"/>
<result column="D4" property="DD4"/>
<association javaType="ccc2" property="card">
<id column="D6" property="DD6" />
<result column="D7" property="DD7"/>
</association>
</resultMap>
<select id="findA" parameterType="Integer"
resultMap="findC">
select A.*,B.* from A,B where A.D1 = B.D6
and A.D1 = #{D1}
</select>
</mapper>