ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

ResultMap结果映射

2022-04-08 17:03:35  阅读:206  来源: 互联网

标签:goods dto String 映射 结果 ResultMap test public categoryName


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

  创建一个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

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有