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

    与其战胜敌人一万次,不如战胜自己一次。
  • 相关阅读:
    fabric-byfn.sh名利解析
    Hyperledger Fabric--byfn.sh 命令分析
    ubuntu修改网络地址
    docker常用命令
    添加daocloud加速器-18.04.2-Ubuntu
    CA/RA简介
    Redhat防火墙
    Linux上Oracle 11g启动与关闭
    redhat网络配置文件详解
    uva1349Optimal Bus Route Design
  • 原文地址:https://www.cnblogs.com/hyjh/p/11986940.html
Copyright © 2011-2022 走看看