MyBatis基础操作

黑马程序员JavaWeb开发教程

文章目录

  • 根据资料中提供的《tlias智能学习辅助系统》页面原型及需求,完成员工管理的需求开发
    • 一、环境准备
      • 1、准备数据库表emp
      • 2、创建一个新的springboot工程,选择引入对应的起步依赖(mybatis、mysql驱动、lombok)
      • 3、application.properties中引入数据库连接信息
      • 4、创建对应的实体类Emp(实体类属性采用驼峰命名)
      • 5、准备Mapper接口EmpMApper
      • 6、准备好的基础工程框架
    • 二、基础操作-删除
      • 1、根据主键ID删除
      • 2、根据主键ID批量删除
    • 三、基础操作-新增
      • (1)SQL语句
      • (2)Mapper接口
      • (3)测试
      • (4)主键返回
    • 四、基础操作-更新
      • (1)SQL语句
      • (2)Mapper接口
      • (3)测试
    • 五、基础操作-查询
      • 1、演示根据ID查询
        • (1)SQL语句
        • (2)Mapper接口
        • (3)测试
      • 2、出现问题
      • 3、问题原因
      • 4、解决方案
      • 5、演示根据条件查询
        • (1)SQL语句
        • (2)Mapper接口
        • (3)测试

根据资料中提供的《tlias智能学习辅助系统》页面原型及需求,完成员工管理的需求开发

一、环境准备

1、准备数据库表emp

  1. 创建表的sql语句
use mybatis;
-- 部门管理
create table dept(
    id int unsigned primary key auto_increment comment'ID,无符号整数,主键,自增长',
    name varchar(20) not null unique comment'部门名称,非空,唯一',
    create_time datetime not null comment'创建时间,非空',
    update_time datetime not null comment'修改时间,非空'
)comment '部门表';

insert into dept (id, name, create_time, update_time)
values  (1,'学工部',now(),now()),
        (2,'教研部',now(),now()),
        (3,'咨询部',now(),now()),
        (4,'就业部',now(),now()),
        (5,'人事部',now(),now());

select * from dept;

-- 员工管理
create table emp(
    id int unsigned primary key auto_increment comment'ID,无符号整数,主键,自增长',
    username varchar(20) not null unique comment'用户名,非空,唯一',
    password varchar(32) default '123456' comment'密码,默认123456',
    name varchar(10) not null comment'姓名,非空',
    gender tinyint unsigned not null comment '性别,无符号整数,,非空,1男,2女',
    image varchar(300) comment'图像',
    job tinyint unsigned comment'工作,无符号整数,1 班主任,2 讲师,3 学工主管, 4 教研主管,5 咨询师',
    entrydate date comment'入职时间',
    dept_id int unsigned comment'部门ID',
    create_time datetime not null comment'创建时间',
    update_time datetime not null comment'修改时间'
)comment'员工表';

INSERT INTO emp(id, username, password, name, gender, image, job, entrydate,dept_id, create_time, update_time)
VALUES  (1,'jinyong','123456','金庸',1,'1.jpg',4,'2000-01-01',2,now(),now()),
        (2,'zhangwuji','123456','张无忌',1,'2.jpg',2,'2015-01-01',2,now(),now()),
        (3,'yangxiao','123456','杨逍',1,'3.jpg',2,'2008-05-01',2,now(),now()),
        (4,'weiyixiao','123456','韦一笑',1,'4.jpg',2,'2007-01-01',2,now(),now()),
        (5,'changyuchun','123456','常遇春',1,'5.jpg',2,'2012-12-05',2,now(),now()),
        (6,'xiaozhao','123456','小昭',2,'6.jpg',3,'2013-09-05',1,now(),now()),
        (7,'jixiaofu','123456','纪晓芙',2,'7.jpg',1,'2005-08-01',1,now(),now()),
        (8,'zhouzhiruo','123456','周芷若',2,'8.jpg',1,'2014-11-09',1,now(),now()),
        (9,'dingminjun','123456','丁敏君',2,'9.jpg',1,'2011-03-11',1,now(),now()),
        (10,'zhaomin','123456','赵敏',2,'10.jpg',1,'2013-09-05',1,now(),now()),
        (11,'luzhangke','123456','鹿杖客',1,'11.jpg',5,'2007-02-01',3,now(),now()),
        (12,'hebiweng','123456','鹤笔翁',1,'12.jpg',5,'2008-08-18',3,now(),now()),
        (13,'fangdongbai','123456','方东白',1,'13.jpg',5,'2012-11-01',3,now(),now()),
        (14,'zhangsanfeng','123456','张三丰',1,'14.jpg',2,'2002-08-01',2,now(),now()),
        (15,'yulianzhou','123456','俞莲舟',1,'15.jpg',2,'2011-05-01',2,now(),now()),
        (16,'songyuanqiao','123456','宋远桥',1,'16.jpg',2,'2010-01-01',2,now(),now()),
        (17,'chenyouliang','123456','陈友谅',1,'17.jpg',NULL,'2015-03-21',NULL,now(),now());

select * from emp;

2、创建一个新的springboot工程,选择引入对应的起步依赖(mybatis、mysql驱动、lombok)

在这里插入图片描述

3、application.properties中引入数据库连接信息

  1. 打开src.main.resources.application.properties,在其中填入配置数据库的信息

    在这里插入图片描述

  2. 配置数据库的信息

# 配置数据库四要素

#驱动类名称
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
#数据库连接的url(将数据库的名字mybatis修改成自己的数据库的名字)
spring.datasource.url=jdbc:mysql://localhost:3306/mybatis
#连接数据库的用户名(将用户名root修改成自己数据库的用户名)
spring.datasource.username=root
#连接数据库的密码(将密码123456修改成自己数据库的密码)
spring.datasource.password=123456

4、创建对应的实体类Emp(实体类属性采用驼峰命名)

  1. 在src.main.java.com.itheima 包下新建包pojo,并在pojo下新建类Emp

    在这里插入图片描述

  2. 实体类属性和数据库中表的属性要同名,表中属性有下划线,实体类中使用驼峰命名即可

package com.itheima.pojo;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.time.LocalDate;
import java.time.LocalDateTime;

@Data
@AllArgsConstructor
@NoArgsConstructor
public class Emp {
    private Integer id; // ID
    private String username; // 用户名
    private String password; // 密码
    private String name; // 姓名
    private Short gender; // 性别,1 男,2 女
    private String image; // 图像url
    private Short job; // 职位,说明:1 班主任,2 讲师,3 学工主管,4 教研主管,5 咨询师
    private LocalDate entrydate; // 入职日期
    private Integer deptId; // 部门id
    private LocalDateTime createTime; // 创建时间
    private LocalDateTime updateTime; // 修改时间
}

5、准备Mapper接口EmpMApper

  1. 在src.main.java.com.itheima 包下新建包mapper,并在mapper下新建接口EmpMapper并加入@Mapper注解

    在这里插入图片描述

  2. EmpMapper接口中的代码

package com.itheima.mapper;

import org.apache.ibatis.annotations.Mapper;

@Mapper
public interface EmpMapper {
}

6、准备好的基础工程框架

在这里插入图片描述

二、基础操作-删除

1、根据主键ID删除

  1. 接口 EmpMapper 中的代码
package com.itheima.mapper;

import org.apache.ibatis.annotations.Delete;
import org.apache.ibatis.annotations.Mapper;

@Mapper // 程序在运行时会自动创建改接口的代理对象,并且会将该代理对象放到IOC当中
public interface EmpMapper {

    //根据ID删除(一般都不需要返回值)
    @Delete("delete from emp where id=#{id}")
    public void deleteById(Integer id);
}

  1. 测试类中的代码(src.test.java.com.itheima.SpringbootMybatisEmpApplicationTests)
package com.itheima;

import com.itheima.mapper.EmpMapper;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;

@SpringBootTest
class SpringbootMybatisEmpApplicationTests {
    @Autowired
    private EmpMapper empMapper;

    @Test
    public void deleteById() {
        empMapper.deleteById(17);
    }

}

  1. 注意事项:如果mapper接口方法形参只要有一个普通类型的参数,#{…}里面的属性名可以随便写,如:#{id}、#{value},但是为了增强可读性还是建议和参数名一样

2、根据主键ID批量删除

三、基础操作-新增

(1)SQL语句

  1. 正式开始之前,现根据要求将SQL语句写出来,插入的SQL语句如下
insert into emp(username,name,gender,image,job,entrydate,dept_id,create_time,update_time)
values('Tom','汤姆',1,'1.jpg',1,'2005-01-01',1,now(),now());

(2)Mapper接口

  1. 在EmpMapper接口中新增一个insert方法,使用 @Insert 注解将SQL语句传入,代码如下
//新增员工
    @Insert("insert into emp(username,name,gender,image,job,entrydate,dept_id,create_time,update_time)" +
            "values(#{username},#{name},#{gender},#{image},#{job},#{entrydate},#{deptId},#{createTime},#{updateTime})")
    public void insert(Emp emp);

(3)测试

  1. 在测试类中编写测试代码(src.test.java.com.itheima.SpringbootMybatisEmpApplicationTests)给Emp中的每个属性赋值
@Test
    public void testInsert() {
        // 构造员工对象
        Emp emp = new Emp();
        // 给员工对象赋值
        emp.setUsername("Tom");
        emp.setName("汤姆");
        emp.setImage("1.jpg");
        emp.setGender((short) 1);
        emp.setJob((short) 1);
        emp.setEntrydate(LocalDate.of(2000, 1, 1));
        emp.setCreateTime(LocalDateTime.now());
        emp.setUpdateTime(LocalDateTime.now());
        emp.setDeptId(1);
        // 测试
        empMapper.insert(emp);
    }

(4)主键返回

  1. 描述:在数据添加成功后,需要获取插入数据库数据的主键

  2. 实现:@Options(useGeneratedKeys = true, keyProperty = “id”)

    在这里插入图片描述

四、基础操作-更新

(1)SQL语句

  1. 根据要求编写用于更新的SQL语句
update emp set username='',name='',gender='',image='',job='',entrydate='',dept_id='',update_time='' where id=1;

(2)Mapper接口

  1. 新增一个修改员工信息的方法,并使用@Update注解将SQL语句传入
//修改员工信息
    @Update("update emp set username = #{username},name = #{name},gender = #{gender},image = #{image},job = #{job},entrydate = #{entrydate},dept_id = #{deptId},update_time = #{updateTime} where id = #{id}")
    public void update(Emp emp);

(3)测试

 //测试修改员工信息
    @Test
    public void testUpdate() {
        // 构造员工对象
        Emp emp = new Emp();
        // 给员工对象赋值
        emp.setId(18);
        emp.setUsername("newTom");
        emp.setName("新汤姆");
        emp.setImage("1.jpg");
        emp.setGender((short) 1);
        emp.setJob((short) 1);
        emp.setEntrydate(LocalDate.of(2000, 1, 1));
        emp.setUpdateTime(LocalDateTime.now());
        emp.setDeptId(1);

        // 测试
        empMapper.update(emp);
    }

五、基础操作-查询

1、演示根据ID查询

(1)SQL语句
select id, username, password, name, gender, image, job, entrydate, dept_id, create_time, update_time from emp where id=18;
或者
select * from emp where id=18;

(2)Mapper接口
  //根据ID查询员工信息
    @Select("select id, username, password, name, gender, image, job, entrydate, dept_id, create_time, update_time from emp where id=#{id}")
    public Emp getEmpById(Integer id);
(3)测试
 @Test
    public void testGetEmpById(){
        Emp emp = empMapper.getEmpById(18);
        System.out.println(emp);
    }

2、出现问题

  1. 可以看到返回值如下,其中 deptId=null, createTime=null, updateTime=null
Emp(id=18, username=newTom, password=123456, name=新汤姆, gender=1, image=1.jpg, job=1, entrydate=2000-01-01, deptId=null, createTime=null, updateTime=null)

3、问题原因

- 实体类属性名 和 数据库表查询返回的字段名一致,mybatis会自动封装
- 如果实体类属性名 和 数据库表查询返回的字段名不一致,不能自动封装

4、解决方案

  1. 方案一:起别名,在SQL语句中,UI不一样的列名其别名,别名和实体类属性名一样
 //方案一:起别名
    @Select("select id, username, password, name, gender, image, job, entrydate, dept_id as deptId, create_time as createTime, update_time as updateTime from emp where id = #{id}")
    public Emp getEmpById(Integer id);
  1. 方案二:手动结果映射,通过@Results以及@Result进行手动结果映射
@Results({
            @Result(column = "dept_id",property = "deptId"),
            @Result(column = "create_time",property = "createTime"),
            @Result(column = "update_time",property = "updateTime")
    })
    @Select("select id, username, password, name, gender, image, job, entrydate, dept_id, create_time,update_time from emp where id = #{id}")
    public Emp getEmpById(Integer id);

  1. 方案三:开启驼峰命名,如果字段名与属性名符合驼峰命名规则,mybatis会自动通过驼峰命名规则映射注意:前提是数据库中的一下划线分割,实体类中是驼峰命名才可以使用这个解决方案,同时这也是推荐的解决方案
    • 首先在src.main.resources.application.properties配置文件中加入:
# 开启 mybatis驼峰命名的映射
mybatis.configuration.map-underscore-to-camel-case=true
    • 之后就可以像之前一样直接写
//    方案三
    @Select("select id, username, password, name, gender, image, job, entrydate, dept_id, create_time,update_time from emp where id = #{id}")
    public Emp getEmpById(Integer id);

5、演示根据条件查询

在这里插入图片描述

(1)SQL语句
select * from emp where name like'%张%' and gender='' and entrydate between '' and '' order by update_time desc;

(2)Mapper接口
  1. 不知道为什么使用的是2.X也需要加@Param注解
//条件查询
    @Select("select * from emp where name like concat('%',#{name},'%') and gender=#{gender} and " +
            "entrydate between #{begin}  and #{end}  order by update_time desc")
    public List<Emp> list(@Param("name") String name, @Param("gender") Short gender, @Param("begin") LocalDate begin, @Param("end") LocalDate end);
(3)测试

@Test
public void testList(){
List list = empMapper.list(“张”, (short) 1, LocalDate.of(2010, 1, 1), LocalDate.of(2020, 1, 1));
System.out.println(list);
}

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

如若内容造成侵权/违法违规/事实不符,请联系我们进行投诉反馈qq邮箱809451989@qq.com,一经查实,立即删除!

相关文章

SpringBoot项目启动,传参有哪些方式?

SpringBoot项目启动&#xff0c;传参有哪些方式&#xff1f; 1.Spring级别的参数 直接在启动 Spring Boot 应用的命令行中使用 -- 后跟参数名和值的方式来传递参数。 记住&#xff1a;一般是对于Spring Boot应用特有的配置参数&#xff0c;确保它们遵循Spring Boot的配置属性命…

PC端微信软件如何多开【详细教程】

现在工作中&#xff0c;很多小伙伴会用到两个微信。如何在PC端同时登录多个微信呢&#xff1f;赶快跟着下面的教程学起来吧 1、创建一个txt文本文件 2、输入以下代码并保存 echo offstart "" "复制粘贴微信的目标地址" 需要开几个微信就复制几行exit示例…

顺序表leetcode刷题(C语言版)

一.移除元素 对于本题&#xff0c;共有两种解法&#xff1a; 思路一&#xff1a;创建新的数组&#xff0c;遍历原数组&#xff0c;将不为value的值放到新数组中&#xff0c;但本题不允许使用新的数组&#xff0c;因此该方法不行 思路二&#xff1a;使用快慢指针&#xff0c;原数…

2.5G交换机 TL-SE2109简单开箱评测,8个2.5G电口+1个10G光口(SFP+)

TPLINK&#xff08;普联&#xff09;的万兆上联的2.5G网管交换机TL-SE2109简单开箱测评。8个2.5电口&#xff0c;1个万兆SFP口。 TL-SH5428 万兆交换机开箱和简单的评测&#xff1a;https://blog.zeruns.tech/archives/707.html WiFi7无线路由器TL-7DR6560简单开箱测评&#x…

震惊!小红书矩阵账号管理-批量发布笔记

“小红书引流软件矩阵工具-笔记批量发” 昨天&#xff0c;有个粉丝急匆匆地来找我&#xff0c;一脸焦急地说&#xff1a;“大佬&#xff0c;我现在运营着好几个小红书账号&#xff0c;每天都要发布内容&#xff0c;可把我忙坏了&#xff0c;有没有什么高效的管理方法啊&#xf…

开源协议的对比和商业上的安全使用

开源协议的对比和商业上的安全使用 开源组件是&#xff1a;“任何人都可以自由使用、更改和共享&#xff08;以修改或未修改的形式&#xff09;的软件”。当今企业依靠开源来加速开发、降低成本和推动创新。对开放源码的糟糕管理可能会使组织面临安全、法律和操作风险。 使用…

Python基础进阶语法

目录&#xff1a; 一、基础语法二、进阶语法 一、基础语法 二、进阶语法 1、列表推导式运用 解析&#xff1a;先循环1到10内的数字&#xff0c;然后过滤大于5的数&#xff0c;赋值到new_list数组中进行打印结果。

重学java 22.面向对象 继承、抽象综合案例

我们纵横交错&#xff0c;最后回到原点 —— 24.4.23 综合案例 流程思维图 代码实现 方式1 利用set方法为属性赋值 父类&#xff1a; public abstract class Development extends Employee{}子类1&#xff1a; public class JavaEE extends Development{Overridepublic void w…

Redis可视化工具RedisInsight

下载地址&#xff1a;RedisInsight - The Best Redis GUIRedisInsight provides an intuitive and efficient graphical interface for Redis, allowing you to interact with your databases and manage your data.https://redis.com/redis-enterprise/redis-insight/#insight…

APP自定义身份证相机(Android +iOS)

基本上同时兼容安卓和苹果的插件都需要付费&#xff0c;这里我找了2个好用的免费插件 1.仅支持安卓&#xff1a;自定义身份证相机&#xff08;支持蒙版自定义&#xff09;&#xff0c;内置蒙版&#xff0c;照片预览&#xff0c;身份证裁剪 - DCloud 插件市场、 2.支持iOS(已测…

前端CSS基础8(盒子模型(margin、border、padding、content))

前端CSS基础8&#xff08;盒子模型&#xff08;margin、border、padding、content&#xff09;&#xff09; CSS盒子模型CSS中常用的长度单位元素的分类&#xff0c;各个元素的显示模式修改元素的显示模式&#xff08;类型&#xff09;盒子模型的组成部分盒子内容区-contentCSS…

激活虚拟环境.ps1“因为在此系统上禁止运行脚本”解决办法

激活虚拟环境.ps1“因为在此系统上禁止运行脚本”解决办法 1.问题收录 Django激活虚拟环境时遇到的&#xff0c;已解决&#xff0c;作以收录&#xff0c;希望能帮到大家 2.分析问题 核心是Powershell的安全策略&#xff0c;将XX命令视为不安全脚本&#xff0c;不允许执行&…

树莓集团有效链接政、企、校,搭建三方合作平台

树莓集团——数字生态产业链建设者&#xff0c;有效链接政、企、校&#xff0c;搭建三方合作平台。集团旗下树莓教育拥有发展数字影像培训十余年的成都王老师摄影培训学校&#xff0c;一家在数字影像教育领域中独树一帜的专业机构。树莓集团凭借其深厚的教育积淀和丰富的实践经…

单片机通讯协议

参考&#xff1a;江科大单片机教程 STM32入门教程-2023版 细致讲解 中文字幕_哔哩哔哩_bilibili IIC通讯协议SPI通信协议UARTCANUSB速度100k-400khz4Mhz-线数2 CLK,DATA4CLK,ENB,IO,OI额外设备一主多从一主多从 一般不用自己写&#xff0c;都有相应的库或官方提供相应的&#…

Mysql用语句创建表/插入列【示例】

一、 创建表 COMMENT表示字段或列的注释 -- 新建student表 CREATE TABLE student (id BIGINT NOT NULL COMMENT 学生id, enroll_date DATE NOT NULL COMMENT 注册时间, NAME VARCHAR(18) DEFAULT NOT NULL COMMENT 学生姓名, deal_flag TINYINT(1) DEFAULT 0 NOT NULL COMM…

linux开发板开机启动向日葵

硬件&#xff1a;orangepi 5 pro 操作系统&#xff1a;ubuntu 20.4 lts 安装向日葵 根据我的实测&#xff0c;arm架构的ubuntu系统只能安装向日葵提供的麒麟系统的那个版本&#xff0c;具体安装方式官网下载页面有 允许任意用户连接到 X11 使用root用户登录后打开终端输入一下…

数据分析学习资源(未完)

1、PDF 数据分析自学攻略 增长黑客&#xff08;AARRR&#xff09; 量化思维

Centos7升级编译器

Centos7默认编译器版本&#xff1a; gcc5.1之前的编译器&#xff0c;默认是C98标准的&#xff0c;若是编译一些支持C高版本的软件时&#xff0c;难免会出现问题。例如&#xff1a;编译最新版jsoncpp&#xff0c;会有如下问题&#xff1a;&#xff08;原因是&#xff1a;std在C9…

从阿里云迁移Redis到AWS的规划和前期准备

在将Redis实例从阿里云迁移到AWS之前,需要进行全面的规划和前期准备。以下九河云提供一些重要的步骤和注意事项: 1. 评估Redis使用情况 首先,您需要评估当前Redis实例的使用情况,包括实例规格、内存使用量、吞吐量、访问模式等。这将有助于选择合适的AWS Redis产品和实例类型…

代码随想录算法训练营day40

题目&#xff1a;343. 整数拆分、96.不同的二叉搜索树 参考链接&#xff1a;代码随想录 343. 整数拆分 思路&#xff1a;五部曲来走。dp数组&#xff0c;dp[i]用于记录拆i得到的最大乘积和&#xff0c;我们要求的也就是dp[n]&#xff1b;递推公式&#xff0c;我们想拆分i&am…
最新文章