其他分享
首页 > 其他分享> > ResultMap结果映射

ResultMap结果映射

作者:互联网

扩展出一个对象对查询结果进行保存

  创建一个dto包src-main-java-com-MyBatis-dto

  dto是一个特殊的JavaBean,JavaBean是一种Java类,符合一定编写规范,是一种实体与信息的规范。

  JavaBean规范:

  (1)必须有1个public 无参构造

  (2)所有属性私有

  (3)属性通过getter、setter方式暴露给其他程序

  (4)类要求可序列化

在dto目录下创建GoodsDTO

 

package com.MyBatis.dto;

import com.MyBatis.entity.Goods;

public class GoodsDTO {
    private Goods goods;
    private String categoryName;
    private String test;

    public Goods getGoods() {
        return goods;
    }
    public void setGoods(Goods goods) {
        this.goods = goods;
    }
    public String getCategoryName() {
        return categoryName;
    }
    public void setCategoryName(String categoryName) {
        this.categoryName = categoryName;
    }
    public String getTest() {
        return test;
    }
    public void setTest(String test) {
        this.test = test;
    }
}

 

在Mapper XML中编写<select>标签并书写SQL语句

<!--结果映射-->
    <resultMap id="rmGoods" type="com.MyBatis.dto.GoodsDTO">
        <!--设置主键字段与属性映射-->
        <id property="goods.goodsId" column="goods_id"></id>
        <!--设置非主键字段与属性映射-->
        <result property="goods.title" column="title"></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="categoryName" column="category_name"></result>
        <result property="test" column="test"></result>
    </resultMap>
    <select id="selectGoodsDTO" resultMap="rmGoods">
        select g.*,c.category_name,'1' as test from t_goods g,t_category c
        where g.category_id = c.category_id
    </select>

测试

    @Test
    public void testSelectGoodsDTO(){
        SqlSession sqlSession=null;
        try{
            sqlSession=MyBatisUtils.openSession();
            List<GoodsDTO> list = sqlSession.selectList("goods.selectGoodsDTO");
            for(GoodsDTO g : list){
                System.out.println(g.getGoods().getTitle());
            }
        }catch (Exception e){
            throw e;
        }finally {
            MyBatisUtils.closeSession(sqlSession);
        }
    }

 

标签:goods,dto,String,映射,结果,ResultMap,test,public,categoryName
来源: https://www.cnblogs.com/nanfeng66/p/16118157.html