Mybatis连结3表查询数据resultMap结果映射
一、前言
Mybatis实现了sql与java代码的分离,达到了解耦合的目的,配置sql语句时有个resultType=""的属性,用于定义sql查询返回结果数据类型,但它有局限性,就是当连表查询的时候,你很难说定义返回的是某一个类型,这时就需要用到一个标签了,那就是resultMap,结果映射.
二、从sql查询结果到模型实体
在深入ResultMap标签前,我们需要了解从SQL查询结果集到JavaBean或POJO实体的过程。
1. 通过JDBC查询得到ResultSet对象
2. 遍历ResultSet对象并将每行数据暂存到HashMap实例中,以结果集的字段名或字段别名为键,以字段值为值
3. 根据ResultMap标签的type属性通过反射实例化领域模型
4. 根据ResultMap标签的type属性和id、result等标签信息将HashMap中的键值对,填充到领域模型实例中并返回
三、ResultMap标签
id属性:标识resultMap,通过它去识别.
type属性:返回值类型,类的全定向名.
autoMapping属性:值为true(默认)|false,是否自动映射。自动映射功能就是自动查找与字段名小写同名的属性名,并调用setter方法。而设置为false后,则需要在`resultMap`内明确注明映射关系才会调用对应的setter方法。
四、ResultMap中子标签
在讲标签时先讲述下数据库中表数据的对应关系,如一对一,一对多,多对多等关系,具体来说,如有一个俱乐部表,一个全员表,一个俱乐部里有许多球员,而许多球员对应一个俱乐部,则俱乐部与球员之间的关系就是一对多与多对一的关系。
<collection>子标签:对应表格关系中的多
<association>子标签:对应表格关系中的一
五、联结三表示例
示例是联结三表,查询结果作为示范,就算联结再多表也能举一反三。这三个表的关系如下图
sql语句联结:http://download.csdn.net/detail/sunrise_zhu/9687991
核心代码:
clubMapper.xml中结果映射
[html]
view plain
copy
<resultMap type="com.sxt.entity.Club" id="clubBean" autoMapping="true"> <result column="cid" property="cid"/> <result column="cname" property="cname"/> <result column="city" property="city"/> <collection property="players" ofType="com.sxt.entity.Player"> <result column="pid" property="pid"/> <result column="pname" property="pname"/> <result column="position" property="position"/> <result column="cid" property="cid"/> <association property="abilities" javaType="com.sxt.entity.Abilities"> <result column="aid" property="aid"/> <result column="pid" property="pid"/> <result column="shoot" property="shoot"/> </association> </collection> </resultMap>
clubMapper.xml中sql语句
[html]
view plain
copy
<select id="joinTwo" resultMap="clubBean"> select c.*,p.*,a.* from clubs c join player p on c.cid = p.cid join abilities a on a.pid = p.pid; </select>
playerMapper.xml中的结果映射:
[html]
view plain
copy
<resultMap type="com.sxt.entity.Player" id="playerBean"> <result column="pid" property="pid" /> <result column="pname" property="pname" /> <result column="position" property="position" /> <result column="cid" property="cid" /> <association property="club" javaType="com.sxt.entity.Club"> <result column="cid" property="cid" /> <result column="cname" property="cname" /> <result column="city" property="city" /> </association> <association property="abilities" javaType="com.sxt.entity.Abilities"> <result column="aid" property="aid"/> <result column="pid" property="pid"/> <result column="shoot" property="shoot"/> </association> </resultMap>
abilitiesMapper.xml结果映射
[html]
view plain
copy
<resultMap type="com.sxt.entity.Abilities" id="abilitiesBean"> <result column="aid" property="aid"/> <result column="pid" property="pid"/> <result column="shoot" property="shoot"/> <association property="player" javaType="com.sxt.entity.Player"> <result column="pid" property="pid"/> <result column="pname" property="pname"/> <result column="position" property="position"/> <result column="cid" property="cid"/> </association>