即Minister类作为Country类的关联属性。 查询的输出结果是:Country{id=2, name='美国', minister=[null]}
<!--mapper.xml内容-->
<!--第二次查询-->
<select id="findMinisterById" resultType="com.abc.beans.Minister"> select mid,mname from minister where countryId = #{cid} </select> <resultMap id="AndSelectCountry" type="com.abc.beans.Country"> <id property="id" column="cid"/> <result property="name" column="cname"/> <collection property="minister" column="cid" ofType="com.abc.beans.Minister" select="findMinisterById"> </collection> </resultMap>
<!--第一次查询--> <select id="findById" resultMap="AndSelectCountry"> select cid,cname from country where cid = #{id} </select>
//测试类
@Test public void test01() { Country country = cmDao.findById(2); System.out.println(country); }
这种错误是不容易找的,因为没有报错信息!!
总结:
1. 在resultMap中的collection或者association范围内:
查看collection标签中column的值是不是第一次所查询 (此时我这个是findById查询)的数据表中的字段名。比如我这个查询出了cid字段,cname字段。
column="cid“,也没有错误
2.在第二次查询的范围内找:
结果找到了,因为 select mid,mname from minister where countryId = #{cid}中mid,mname和Minister实体类的属性不一致,导致数据没法封装进Minister,所以Country的minister属性才为空。
mybatis中用resultMap解决属性名和字段名不一致的问题
最终又增加一个resultMap标签解决了:
<select id="findMinisterById" resultMap="com"> select mid,mname from minister where countryId = #{cid} </select> <resultMap id="com" type="com.abc.beans.Minister"> <id property="id" column="mid"/> <result property="name" column="mname"/> </resultMap> <resultMap id="AndSelectCountry" type="com.abc.beans.Country"> <id property="id" column="cid"/> <result property="name" column="cname"/> <collection property="minister" column="cid" ofType="com.abc.beans.Minister" select="findMinisterById"> </collection> </resultMap> <select id="findById" resultMap="AndSelectCountry"> select cid,cname from country where cid = #{id} </select>
输出结果:Country{id=2, name='美国', minister=[Minister{id=4, name='赵柳'}, Minister{id=3, name='王五'}]}