基于Maven工程下的MyBatis基本使用之SQL传单/多参、多表关联查询

执键写春秋
• 阅读 1939

MyBatis基本使用

声明:基于《基于Maven工程下的MyBatis框架+MySQL+连接池的数据查询操作》进一步拓展,相关配置文件、数据文件可阅上篇。

SQL传单/多参

    在goods.xml新增两个<select>:

    <!--单参数传参,使用paramterType指定的数据类型即可,SQL中#{value}提取参数-->
    <select id="selectById" parameterType="Integer" resultType="com.imooc.mybatis.entity.Goods">
        select * from t_goods where goods_id=#{value}
    </select>
    <!--多参数传参,使用paramterType指定Map接口,SQL中#{value}提取参数,这里的value为Map的key值-->
    <select id="selectByPriceRange" parameterType="java.util.Map" resultType="com.imooc.mybatis.entity.Goods">
        select * from t_goods where current_price between #{min} and #{max}
        order by current_price limit 0,#{limit}
    </select>
在MyBatisTest.java测试类中新增两个方法:

@Test
    public void testSelectById(){
        SqlSession sqlSession = null;
        try {
            sqlSession = MyBatisUtils.openSession();
            // 进行查询,传入的参数取的是在goods.xml文件的namespace名称和select id
            Goods goods=sqlSession.selectOne("goods.selectById",1602);
            System.out.println(goods);

        } catch (Exception e) {
            throw e;
        } finally {
            MyBatisUtils.closeSession(sqlSession);
        }
    }
    @Test
    public void testSelectByPriceRange(){
        SqlSession sqlSession = null;
        try {
            sqlSession = MyBatisUtils.openSession();
            // 进行查询,传入的参数取的是在goods.xml文件的namespace名称和select id
            Map param = new HashMap();
            param.put("min",100);
            param.put("max",500);
            param.put("limit",10);

            List<Goods> list=sqlSession.selectList("goods.selectByPriceRange",param);
            for (Goods goods : list) {
                System.out.println(goods.getTitle()+"--"+goods.getCurrentPrice());
            }
        } catch (Exception e) {
            throw e;
        } finally {
            MyBatisUtils.closeSession(sqlSession);
        }
    }

多表关联查询【Map--KEY对应数据库中的字段名】

新增t_category种类表

create table t_category
(
    category_id    int auto_increment comment '产品分类'
        primary key,
    category_name  varchar(32) not null comment '分类名称',
    parent_id      int         null comment '上级分类',
    category_level int         not null comment '级别',
    category_order int         not null comment '排序'
)
 在goods.xml新增两个<select>,随用其一,两者区别是让返回的Map集合无序/有序

<select id="selectGoodsMap" resultType="java.util.Map">
        select g.*,c.category_name from t_goods g,t_category c
        where g.category_id=c.category_id
    </select>

    <select id="selectGoodsLinkedHashMap" resultType="java.util.LinkedHashMap">
        select g.*,c.category_name from t_goods g,t_category c
        where g.category_id=c.category_id
    </select>
在MyBatisTest.java测试类中新增两个方法:

//java.util.Map
 @Test
    public void testSelectGoodsMap(){
        SqlSession sqlSession = null;
        try {
            sqlSession = MyBatisUtils.openSession();
            // 进行查询,传入的参数取的是在goods.xml文件的namespace名称和select id
            List<Map> list=sqlSession.selectList("goods.selectGoodsMap");
            for (Map map : list) {
                System.out.println(map);
            }
        } catch (Exception e) {
            throw e;
        } finally {
            MyBatisUtils.closeSession(sqlSession);
        }
    }
//java.util.LinkedHashMap
    @Test
    public void testSelectGoodsLinkedHashMap(){
        SqlSession sqlSession = null;
        try {
            sqlSession = MyBatisUtils.openSession();
            // 进行查询,传入的参数取的是在goods.xml文件的namespace名称和select id
            List<Map> list=sqlSession.selectList("goods.selectGoodsLinkedHashMap");
            for (Map map : list) {
                System.out.println(map);
            }
        } catch (Exception e) {
            throw e;
        } finally {
            MyBatisUtils.closeSession(sqlSession);
        }
    }

基于Maven工程下的MyBatis基本使用之SQL传单/多参、多表关联查询 基于Maven工程下的MyBatis基本使用之SQL传单/多参、多表关联查询

多表关联查询【Entity--KEY对应实体类中的字段名】

因为要用到实体类Goods,而多表查询的category_name属性值不被Goods包含,所以这里要对Goods进行扩展,但不在原有的实体类上修改,而是新建拓展类GoodsDTO.java,其中test属性是我测试属性,用AS命令添加的属性

package com.imooc.mybatis.dto;

import com.imooc.mybatis.entity.Goods;

/**
 * @Auther 徐士成
 * @Date 2021-06-22 14:18
 */
public class GoodsDTO {
    private Goods goods = new 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;
    }

    @Override
    public String toString() {
        return "GoodsDTO{" +
                "goods=" + goods +
                ", categoryName='" + categoryName + '\'' +
                ", test='" + test + '\'' +
                '}';
    }
}

这里借助resultMap结果集完成实体类映射:

<resultMap id="rmGoods" type="com.imooc.mybatis.dto.GoodsDTO">
        <id column="goods_id" property="goods.goodsId"></id>
        <result column="title" property="goods.title"></result>
        <result column="original_cost" property="goods.originalCost"></result>
        <result column="current_price" property="goods.currentPrice"></result>
        <result column="discount" property="goods.discount"></result>
        <result column="is_free_delivery" property="goods.isFreeDelivery"></result>
        <result column="category_id" property="goods.categoryId"></result>
        <result column="category_name" property="categoryName"></result>
        <result column="test" property="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();
            // 进行查询,传入的参数取的是在goods.xml文件的namespace名称和select id
            List<GoodsDTO> list=sqlSession.selectList("goods.selectGoodsDTO");
            for (GoodsDTO goodsDTO : list) {
                System.out.println(goodsDTO);
            }
        } catch (Exception e) {
            throw e;
        } finally {
            MyBatisUtils.closeSession(sqlSession);
        }
    }
点赞
收藏
评论区
推荐文章
blmius blmius
2年前
MySQL:[Err] 1292 - Incorrect datetime value: ‘0000-00-00 00:00:00‘ for column ‘CREATE_TIME‘ at row 1
文章目录问题用navicat导入数据时,报错:原因这是因为当前的MySQL不支持datetime为0的情况。解决修改sql\mode:sql\mode:SQLMode定义了MySQL应支持的SQL语法、数据校验等,这样可以更容易地在不同的环境中使用MySQL。全局s
执键写春秋 执键写春秋
2年前
基于Maven工程下的MyBatis基本使用之数据插入【回填】、修改与删除
MyBatis基本使用声明:基于《基于Maven工程下的MyBatis框架MySQL连接池的数据查询操作》与《基于Maven工程下的MyBatis基本使用之SQL传单/多参、多表关联查询》进一步拓展,相关配置文件、数据文件可阅以上两篇。数据插入<insert,使用<selectKey进行回填自动生成主键值<!需要明确编写获取最新主键的SQL语句<in
Jacquelyn38 Jacquelyn38
2年前
2020年前端实用代码段,为你的工作保驾护航
有空的时候,自己总结了几个代码段,在开发中也经常使用,谢谢。1、使用解构获取json数据let jsonData  id: 1,status: "OK",data: 'a', 'b';let  id, status, data: number   jsonData;console.log(id, status, number )
皕杰报表之UUID
​在我们用皕杰报表工具设计填报报表时,如何在新增行里自动增加id呢?能新增整数排序id吗?目前可以在新增行里自动增加id,但只能用uuid函数增加UUID编码,不能新增整数排序id。uuid函数说明:获取一个UUID,可以在填报表中用来创建数据ID语法:uuid()或uuid(sep)参数说明:sep布尔值,生成的uuid中是否包含分隔符'',缺省为
Stella981 Stella981
2年前
Python3:sqlalchemy对mysql数据库操作,非sql语句
Python3:sqlalchemy对mysql数据库操作,非sql语句python3authorlizmdatetime2018020110:00:00coding:utf8'''
Stella981 Stella981
2年前
MyBatis基于Maven的入门
主要内容如下: 1.myBatis在maven中的配置 2.myBatis在工程中的config配置文件3.myBatis为Bean和表的映射文件4.myBatis基本的使用 myBatis在maven中的配置,在pom.xml中增加内容       1.增加依赖 ,mybatis的,还有mysql的驱动的
Wesley13 Wesley13
2年前
00:Java简单了解
浅谈Java之概述Java是SUN(StanfordUniversityNetwork),斯坦福大学网络公司)1995年推出的一门高级编程语言。Java是一种面向Internet的编程语言。随着Java技术在web方面的不断成熟,已经成为Web应用程序的首选开发语言。Java是简单易学,完全面向对象,安全可靠,与平台无关的编程语言。
Wesley13 Wesley13
2年前
Oracle一张表中实现对一个字段不同值和总值的统计(多个count)
需求:统计WAIT\_ORDER表中的工单总数、未处理工单总数、已完成工单总数、未完成工单总数。表结构:为了举例子方便,WAIT\_ORDER表只有两个字段,分别是ID、STATUS,其中STATUS为工单的状态。1表示未处理,2表示已完成,3表示未完成总数。 SQL:  1.SELECT   2
Wesley13 Wesley13
2年前
MySQL部分从库上面因为大量的临时表tmp_table造成慢查询
背景描述Time:20190124T00:08:14.70572408:00User@Host:@Id:Schema:sentrymetaLast_errno:0Killed:0Query_time:0.315758Lock_
Python进阶者 Python进阶者
3个月前
Excel中这日期老是出来00:00:00,怎么用Pandas把这个去除
大家好,我是皮皮。一、前言前几天在Python白银交流群【上海新年人】问了一个Pandas数据筛选的问题。问题如下:这日期老是出来00:00:00,怎么把这个去除。二、实现过程后来【论草莓如何成为冻干莓】给了一个思路和代码如下:pd.toexcel之前把这