【MyBatis】查询语句汇总

news2024/10/6 4:06:08

定义一个Car类:

/**
 * 封装汽车相关信息的 pojo类
 */
public class Car {
    // 数据库表当中的字段应该和pojo类的属性一一对应
    // 建议使用包装类, 这样可以防止null的问题
    private Long id;
    private String carNum;
    private String brand;
    private Double guidePrice;
    private String produceTime;
    private String carType;
    public Car() {
    }
    public Car(Long id, String carNum, String brand, Double guidePrice, String produceTime, String carType) {
        this.id = id;
        this.carNum = carNum;
        this.brand = brand;
        this.guidePrice = guidePrice;
        this.produceTime = produceTime;
        this.carType = carType;
    }
    public Long getId() {return id;}
    public void setId(Long id) {this.id = id;}
    @Override
    public String toString() {
        return "Car{" +
                "id=" + id +
                ", carNum='" + carNum + '\'' +
                ", brand='" + brand + '\'' +
                ", guidePrice=" + guidePrice +
                ", produceTime='" + produceTime + '\'' +
                ", carType='" + carType + '\'' +
                '}';
    }
    public String getCarNum() {return carNum;}
    public void setCarNum(String carNum) {this.carNum = carNum;}
    public String getBrand() {return brand;}
    public void setBrand(String brand) {this.brand = brand;}
    public Double getGuidePrice() {return guidePrice;}
    public void setGuidePrice(Double guidePrice) {this.guidePrice = guidePrice;}
    public String getProduceTime() {return produceTime;}
    public void setProduceTime(String produceTime) {this.produceTime = produceTime;}
    public String getCarType() {return carType;}
    public void setCarType(String carType) {this.carType = carType;}
}

1. 查询之返回Car:

// CarMapper.xml
// 必须要指定返回结果的类型
<select id="selectById" resultType="Car">
    <!-- select * from car where id = #{id}-->
    // 列名要和pojo类中的属性名要对的上, 否则查出来为null
    select
        id, car_num as carNum, brand, guide_price as guidePrice,
        produce_time as produceTimme,
        car_type as catType
    from
        car
    where
        id = #{id}
</select>

// 接口
public interface CarMapper{
    // 根据id查询Car信息
    Car selectById(Long id);
}

// @test
public static void main(String[] args) {
    SqlSession sqlSession = SqlSessionUtil.openSession();
    CarMapper mapper = sqlSession.getMapper(CarMapper.class);
    
    Car car = mapper.selectById(16L);
    System.out.println(car);
    
    sqlSession.close();
}

2. 查询之返回多个Car:

// CarMapper.xml
// 必须要指定返回结果的类型
<select id="selectAll" resultType="Car">
    <!-- select * from car where id = #{id}-->
    // 列名要和pojo类中的属性名要对的上, 否则查出来为null
    select
        id, car_num as carNum, brand, guide_price as guidePrice,
        produce_time as produceTimme,
        car_type as catType
    from
        car
</select>

// 接口
public interface CarMapper{
    // 查询所有Car信息
    List<Car> selectAll();
}

// @test
public static void main(String[] args) {
    SqlSession sqlSession = SqlSessionUtil.openSession();
    CarMapper mapper = sqlSession.getMapper(CarMapper.class);
    
    List<Car> cars = mapper.selectAll();
    cars.forEach(car -> System.out.println(car));
    
    sqlSession.close();
}

3. 查询之返回Map:

  • map的key都是数据库的列名

// CarMapper.xml
// resultType="java.util.Map" 有别名: "map"
<select id="selectByIdRetMap" resultType="map">
    // 返回的类型是个map, 不需要和Car类属性匹配了
    select * from car where id = #{id}
</select>

// 接口
public interface CarMapper{
    // 根据id获取汽车信息, 将信息放到Map集合中
    Map<String, Object> selectByIdRetMap(Long id);
}

// @test
public static void main(String[] args) {
    SqlSession sqlSession = SqlSessionUtil.openSession();
    CarMapper mapper = sqlSession.getMapper(CarMapper.class);
    
    Map<String, Object> car = mapper.selectByIdRetMap(16L);
    System.out.println(car);
    sqlSession.close();
}

4. 查询之返回多个Map:

// CarMapper.xml
// resultType="map", 不能写"list"
<select id="selectAllRetListMap" resultType="map">
    // 返回的类型是个map, 不需要和Car类属性匹配了
    select * from car 
</select>

// 接口
public interface CarMapper{
    // 查询所有的car信息, 返回一个存放Map集合的List集合
    List<Map<String, Object>> selectAllRetListMap();
}

// @test
public static void main(String[] args) {
    SqlSession sqlSession = SqlSessionUtil.openSession();
    CarMapper mapper = sqlSession.getMapper(CarMapper.class);
    
    List<Map<String, Object>> maps = mapper.selectAllRetListMap();
    maps.forEach(map -> System.out.println(map));
    sqlSession.close();
}

5. 查询之返回Map<String,Map>:

  • 拿Car的id做key, 以后取出对应的Map集合时更加方便

  • 需要使用到@MapKey注解

// CarMapper.xml
// resultType="map", 不能写"list"
<select id="selectAllRetMap" resultType="map">
    // 返回的类型是个map, 不需要和Car类属性匹配了
    select * from car 
</select>

// 接口
public interface CarMapper{
    // 查询所有的Car, 返回一个Map集合
    // Map集合的key是每条记录的主键值
    // Map集合的value是每条记录
    @MapKey("id") // 将查询结果的id值作为一个大map集合的key
    Map<Long,Map<String, Object>> selectAllRetMap();
}

// @test
public static void main(String[] args) {
    SqlSession sqlSession = SqlSessionUtil.openSession();
    CarMapper mapper = sqlSession.getMapper(CarMapper.class);
    
    Map<Long,Map<String, Object>> maps = mapper.selectAllRetMap();
    System.out.println(maps);
    sqlSession.close();
}

6. resultMap结果映射:

查询结果的列名和Java对象的属性名对应不上怎么办?

  1. as给列起别名

// CarMapper.xml
// 必须要指定返回结果的类型
<select id="selectAll" resultType="Car">
    select
       id, 
        car_num as carNum, 
        brand, 
        guide_price as guidePrice,
        produce_time as produceTimme,
        car_type as catType
    from
        car
</select>

// 接口
public interface CarMapper{
    // 查询所有Car信息
    List<Car> selectAll();
}

// @test
public static void main(String[] args) {
    SqlSession sqlSession = SqlSessionUtil.openSession();
    CarMapper mapper = sqlSession.getMapper(CarMapper.class);
    
    List<Car> cars = mapper.selectAll();
    cars.forEach(car -> System.out.println(car));
    
    sqlSession.close();
}
  1. 使用resultMap进行结果映射

// CarMapper.xml

<resultMap id="carResultMap" type="Car">
    // 如果数据库表中有主键, 一般都是有主键的, 否则不符合数据库设计第一范式
    // 如果有主键, 建议这里面配置一个id标签, 这样是为了提高效率
    <id property ="id" column="id"/>
    // property后面填写的是POJO类的属性名
    // column后面填写的是数据库的字段名
    <result property="carNum" column="car_num"/>
    // 如果属性名和字段名相同, 可以不配置
    <result property="brand" column="brand"/>    
    <result property="guidePrice" column="guide_price"/>
    <result property="produceTime" column="produce_time"/>
    <result property="carType" column="car_type"/>
</resultMap>

// resultMap属性用来指定使用哪个结果映射, resultMap后面的值是resultMap的id
<select id="selectAllByResultMap" resultMap="carResultMap">
    select * from car 
</select>

// 接口
public interface CarMapper{
    // 查询所有Car信息, 使用resultMap标签
    List<Car> selectAllByResultMap();
}

// @test
public static void main(String[] args) {
    SqlSession sqlSession = SqlSessionUtil.openSession();
    CarMapper mapper = sqlSession.getMapper(CarMapper.class);
    
    List<Car> cars = mapper.selectAllByResultMap();
    cars.forEach(car -> System.out.println(car));
    
    sqlSession.close();
}
  1. 是否开启驼峰命名自动映射(配置settings)

  • 使用这种方式的前提是: 属性遵循java命名规范, 数据库的列名遵循sql的命名规范

  • java命名规范: 首字母小写, 后面每个单词首字母大写, 遵循驼峰命名方式

  • sql命名规范: 全部小写, 单词之间采用下划线分割

如何启用该功能呢? 需要在mybatis-config.xml文件中配置
    
// 放在properties标签后面
<settings>
    <setting name="mapUnderscoreToCameCase" value="true">
</settings>

// CarMapper.xml
<select id="selectAllBymapUnderscoreToCameCase" resultType="Car">
    select * from car
</select>

// 接口
public interface CarMapper{
    // 查询所有Car信息, 启用驼峰命名自动映射机制
    List<Car> selectAllBymapUnderscoreToCameCase();
}

// @test
public static void main(String[] args) {
    SqlSession sqlSession = SqlSessionUtil.openSession();
    CarMapper mapper = sqlSession.getMapper(CarMapper.class);
    
    List<Car> cars = mapper.selectAllBymapUnderscoreToCameCase();
    cars.forEach(car -> System.out.println(car));
    
    sqlSession.close();
}

7. 查询之返回总记录条数:

// CarMapper.xml
// resultType后面也可以写上java.lang.Long
<select id="selectTotal" resultType="long">
    select count(*) from car
</select>

// 接口
public interface CarMapper{
    // 获取Car的总记录条数
    Long selectTotal();
}

// @test
public static void main(String[] args) {
    SqlSession sqlSession = SqlSessionUtil.openSession();
    CarMapper mapper = sqlSession.getMapper(CarMapper.class);
    
    Long nums = mapper.selectTotal();
    System.out.println(nums);
    
    sqlSession.close();
}

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/196006.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

MATLAB入门——线性规划、非线性规划、多目标规划

4-1 线性规划_哔哩哔哩_bilibili 4-2 非线性规划_哔哩哔哩_bilibili 4-3 多目标规划_哔哩哔哩_bilibili 1.线性规划 有限条件下&#xff0c;最大收益 1. 例题 例题&#xff1a;张麻子既要攻碉楼又要追替身&#xff0c;他们一伙6人&#xff0c;总共1200发子弹;每有一人攻确…

【GCC】1: RTCP RR接收端生成

m79 代码。参考bytewoods 大神的以下文章:WebRTC 基于GCC的拥塞控制(上) WebRTC 基于GCC的拥塞控制(下)虽然可以拿到估算的带宽但是rtcp 总是malformed packet个 有必要带着问题跟进下整个过程 RR报文 基于丢包率的码率控制运行在发送端,依靠RTCP RR报文进行工作。* report b…

Vue2低代码平台搭建(一)

前言 大家好,我是L丶Y,这一次,我们来聊一聊前端低代码平台的构建。近些年来,随着Saas行业的高速发展,低代码的概念也逐渐流行了起来,而低代码产品也越来越多的出现在我们的身边,像国外的Mendix,国内的宜搭、苍穹、简道云等等,想通过这篇文章与大家对于前端低代码平台…

如何使用Baklib搭建企业内部wiki

Wiki 是一个协同著作平台或称开放编辑系统。我们可以用Wiki来建设帮助系统&#xff0c;知识库系统。国内公共wiki最著名就是百度百科&#xff0c;国外则是基维百科&#xff1b;Wiki最著名的例子之一是维基百科&#xff0c;它在MediaWiki上运行&#xff0c;任何拥有Web浏览器的人…

QT opencv 学习day02 基本数据结构 point Scalar Size Rect Mat 等等

1.point &#xff08;画点&#xff09; 1. 函数原型&#xff1a; //二维的点 typedef Point_<int> Point2i; typedef Point_<int64> Point2l; typedef Point_<float> Point2f; typedef Point_<double> Point2d; typedef Point2i Point;//三维的点…

EasyExcel 实现 批量生成多sheet多Excel打包zip下载

目录说明需求场景实现1、准备一个excel模板2、把整个excel模板放在resources里面3、重点代码效果图说明 需求场景 导出学校中高年级的学生信息&#xff0c;根据班级名称分组&#xff0c;一个班级一个excel导出&#xff0c;如果多个excel需要打包成zip压缩包下载&#xff0c;一…

Linux应用编程-音频应用编程-语音转文字项目

文章目录前言Linux语音识别alsa-lib简介&#xff1a;安装alsa-lib库&#xff1a;API调用录音相关概念样本长度&#xff08;Sample&#xff09;声道数&#xff08;channel&#xff09;帧&#xff08;frame&#xff09;周期&#xff08;period&#xff09;采样率&#xff08;Samp…

springboot整合JSR303参数校验与全局异常处理

一、前言 我们在日常开发中&#xff0c;避不开的就是参数校验&#xff0c;有人说前端不是会在表单中进行校验的吗&#xff1f;在后端中&#xff0c;我们可以直接不管前端怎么样判断过滤&#xff0c;我们后端都需要进行再次判断&#xff0c;为了安全。因为前端很容易拜托&#…

[面试八股] Mysql

1、Mysql中的索引类型 &#xff08;1&#xff09;普通索引&#xff08;2&#xff09;唯一索引&#xff08;3&#xff09;主键索引&#xff08;4&#xff09;组合索引&#xff08;5&#xff09;全文索引 缺点 1、虽然索引大大提高了查询速度&#xff0c;同时却会降低更新表的速…

Mysql高级部分学习笔记(二)——事务锁

一、buffer pool 1.1 缓冲池&#xff08;buffer pool&#xff09; 简介&#xff1a;InnoDB是基于磁盘存储的&#xff0c;并将其中的数据按页的方式进行管理。因此InnoDB可视为基于磁盘的数据库系统。由于CPU的速度和磁盘IO速度的巨大鸿沟&#xff0c;需要**缓冲池(buffer poo…

windows下通过uiAutomation技术获取ui元素

最近接个需求&#xff0c;要求获取 windows 下 ui 元素&#xff0c;经一番搜索后了解到可通过工具 UISpy.exe 或 inspect.exe 来进行查看。以软件 davinci resolve 为例&#xff1a; 右侧即 UISpy 工具&#xff0c;根据内容可以看出已捕获到 davinci 界面的各属性及对应值。而 …

ItextPdf 字体显示差异分析与处理

ItextPdf 同span下字体显示差异分析与处理 在文章itext7 字体问题解答与相应源代码分析 中是分析了框架的字体设置与相关代码&#xff0c;在本篇文章里将对其生效效果进行分析和相关问题进行处理&#xff08;可持续更新&#xff0c;问题请留言&#xff09; 问题一 问题说明&…

将无风险资产与两种风险资产进行组合

目录 最优风险资产组合。 计算权重的公式。 应用。 最优风险资产组合。 曲线 AB 是两种风险资产的权衡取舍线。 A 点为资产组合中仅有风险资产 1 的情况。将 O 点与 A 点相连&#xff0c;便得到无风险资产与单个风险资产的权衡取舍线。 实际上&#xff0c;曲线 AB 上任一点…

【青训营】分布式理论初探

本文内容总结自 字节跳动青年训练营 第五届后端组 分布式理论初探 一、概述 分布式系统是计算机程序的集合&#xff0c;这些程序利用横跨多个独立计算节点的计算资源实现共同目标&#xff0c;可分为分布式计算、分布式存储、分布式数据库。 其优势是&#xff1a;去中心化、…

ESP32设备驱动-TEA5767收音机模块驱动

TEA5767收音机模块驱动 1、TEA5767介绍 TEA5767HN 是一款用于低压应用的单芯片电子调谐 FM 立体声收音机,具有完全集成的中频 (IF) 选择性和解调功能,频率范围从76—108MHZ自动数字调谐。 该收音机完全无需调整,高灵敏度,高稳定性,低噪音,收音模块。只需要最少的小型低…

Win10安装MySQL、Pycharm连接Mysql、Pycharm中运行django

目录 一、windows系统mysql相关操作 1、检查当前系统是否已安装mysql 1. 按win r 键&#xff08;调出运行窗口&#xff09; 2. 输入service.msc&#xff0c;点击[ 确定 】 3.打开服务列表 - 检查是否有mysql服务 2、windows安装mysql 1.下载mysql 2. 解压 mysql 到自己…

【面试题:三个线程轮流打印A ,B,C】

面试题&#xff1a;三个线程轮流打印A &#xff0c;B&#xff0c;C面试介绍说明思考方案代码实现Print 打印基类APrint 打印字符A 线程CPrint 打印字符C 线程PrintConstant 常量类StrRun 启动类测试结果总结面试介绍说明 当时是2022 年3月 在深圳面试的一家公司。由于疫情比较…

内网渗透(三)之基础知识-域环境的介绍和优点

系列文章 内网渗透(一)之基础知识-内网渗透介绍和概述 内网渗透(二)之基础知识-工作组介绍 注&#xff1a;阅读本编文章前&#xff0c;请先阅读系列文章&#xff0c;以免造成看不懂的情况&#xff01;&#xff01; 域介绍 域的介绍 Windows域是计算机网络的一种形式&#…

DMTet 阅读笔记

介绍 主页 https://nv-tlabs.github.io/DMTet/论文pdf https://nv-tlabs.github.io/DMTet/assets/dmtet.pdf视频汇报 https://slideslive.com/38967642/deep-marching-tetrahedra-a-hybrid-representation-for-highresolution-3d-shape-synthesis?refhomepage疑似代码 在nvdi…

【手写 Promise 源码】第十八篇 - EventLoop 简介

theme: fancy 一&#xff0c;前言 近期公司项目比较忙&#xff0c;粘了老博客几篇 Spring 源码来充数&#xff0c;周末腾出时间把 Promise 做个收尾&#xff1b; 在开始 EventLoop 前&#xff0c;我对 Promise 源码部分进行了简单回顾&#xff0c;并更新了【Promise 源码学习…