zoukankan      html  css  js  c++  java
  • 使用mybatis进行一对多嵌套查询时出错:输出结果:Country{id=2, name='美国', minister=[null]}

    即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='王五'}]}

    与其战胜敌人一万次,不如战胜自己一次。
  • 相关阅读:
    转战物联网·基础篇06-深入理解MQTT协议之基本术语
    转战物联网·基础篇05-通俗理解MQTT协议的实现原理和异步方式
    转战物联网&#183;基础篇04-不可不知的进制关系与数据传输的本质
    转战物联网·基础篇03-从JSON数据到短指令谈思维的转变
    转战物联网·基础篇02-物联网中的角儿
    转战物联网·基础篇01-物联网之我见
    nRF24L01+组网方式及防撞(防冲突)机制的实战分享
    ElementUi中el-table分页效果
    原生无缝Banner轮播图
    详解立即执行函数(function(){}()),(function(){})()
  • 原文地址:https://www.cnblogs.com/hyjh/p/11986940.html
Copyright © 2011-2022 走看看