关于resultMap中的result标签使用的疑问

来源:3-2 ManyToOne对象关联查询

qq_森林中的小熊_0

2019-10-27 11:40:47

<!-- 映射结果-->
<resultMap id="rmGoods" type="com.imooc.mybatis.dto.GoodsDTO">
    <!-- 设置主键字段与属性映射-->
    <id property="goods.goodsId" column="goods_id"></id>
    <!--设置非主键字段与属性映射-->
    <result property="goods.title" column="title"></result>
    <result property="goods.originalCost" column="original_cost"></result>
    <result property="goods.currentPrice" column="current_price"></result>
    <result property="goods.discount" column="discount"></result>
    <result property="goods.isFreeDelivery" column="is_free_delivery"></result>
    <result property="goods.categoryId" column="category_id"></result>
    <result property="category.categoryId" column="category_id"></result>
    <result property="category.categoryName" column="category_name"></result>
    <result property="category.parentId" column="parent_id"></result>
    <result property="category.categoryLevel" column="category_level"></result>
    <result property="category.categoryOrder" column="category_order"></result>
    <result property="test" column="test"/>
</resultMap>
<select id="selectGoodsDTO" resultMap="rmGoods">
    SELECT g.* ,c.*,"1" AS test FROM t_goods g,t_category c
    WHERE g.category_id = c.category_id
</select>

为什么之前课上提到的多表联查resultMap里必须要加result标签来映射,而这节课一对多或多对一这样的查询

里面就不需要加result标签了呢

<resultMap id="rmGoods1" type="com.imooc.mybatis.entity.Goods">
    <!-- 映射goods对象的主键到goods_id字段 -->
    <id column="goods_id" property="goodsId"></id>
    <!--
        collection的含义是,在
        select * from t_goods limit 0,1 得到结果后,对所有Goods对象遍历得到goods_id字段值,
        并代入到goodsDetail命名空间的selectByGoodsId的SQL中执行查询,
        将得到的"商品详情"集合赋值给goodsDetails List对象.
    -->
    <collection property="goodsDetails" select="goodsDetail.selectByGoodsId"
                column="goods_id"/>
</resultMap>
<select id="selectOneToMany" resultMap="rmGoods1">
    SELECT * FROM t_goods LIMIT 0,10
</select>


写回答

1回答

芝芝兰兰

2019-10-27

同学你好。这是因为Goods中的属性和表中的字段是一一对应的,符合驼峰命名的转换。也即是数据库表中的“_”分割的位置,属性名对应字母转换为大写。所以MyBatis在没有指定result时,也可以自动将列转换为属性

http://img.mukewang.com/climg/5db536f90941478308720275.jpg

http://img.mukewang.com/climg/5db53bde096583ba12320437.jpg

而在之前的resultMap中,对应的type为GoodsDTO,并没有一张表和这个对象对应。所以指定result,将列映射到不同的属性中去。


如果解答了同学的疑问,望采纳~

祝学习愉快~

0

0 学习 · 8016 问题

查看课程