[JavaWeb]【八】web后端开发-Mybatis

news2024/9/25 15:26:14

目录

一 介绍

二 Mybatis的入门

2.1 快速入门

 2.1.1 准备SpringBoot工程

2.1.2 创建数据库mybatis以及对应库表user

2.1.3 创建User实体类

 2.1.4 配置application.properties数据库连接信息

2.1.5 编写sql语句(注解方式)

2.1.6 测试运行 

 2.1.7 配置SQL提示

2.2 JDBC介绍(了解)

2.2.1 JDBC 介绍

2.2.2 jdbc与Mybatis对比

2.3 数据库连接池(了解)

2.3.1 概念

2.3.2 mybatis切换Druid(德鲁伊)连接池

 2.3.3 总结

2.4 lombok

三 Mybatis的基础操作

3.1 准备工作

3.1.1 数据脚本在mybatis表执行脚本

3.1.2 创建一个springboot项目 

3.1.3 application.properties配置

3.1.4 创建对应实体类Emp

3.1.5 准备Mapper接口EmpMapper

3.2 日志输出

3.2.1 性能高 

 3.2.2 更安全

 3.2.3 总结 使用#

3.3 删除

 3.3.1 EmpMapper接口添加 删除方法

3.3.2 新增测试方法

3.4 新增

3.4.1 EmpMapper接口添加 新增方法

3.4.2 新增测试方法 

3.4.3 主键返回

3.4.4 总结 

3.5 更新

3.5.1 EmpMapper接口添加 更新方法

3.5.2 新增测试方法

3.6 查询

3.6.1 EmpMapper接口添加 查询方法

3.6.2 新增测试方法

3.6.3 数据封装

 3.6.3.1 方案一 (不推荐):当数据库字段与实体类字段不一致时取别名

3.6.3.2 方案二(不推荐) :通过@Results, @Result注解手动映射封装

 3.6.3.3 方案三(推荐):开启mybatis的驼峰命名自动映射开关

3.7 查询(条件查询)

3.7.1 EmpMapper接口添加 条件查询方法

3.7.2 新增测试方法

 3.7.3 使用concat解决使用'%$name}%'问题

四 XML映射文件

4.1 XML映射规范

4.1.1 第一步: 

 4.1.2 第二步:​编辑

4.1.3 第三步

4.1.4 验证

 4.2 mybatisx插件

4.3 总结

五 Mybatis的动态SQL

5.1

5.1.1 优化EmpMapper.xml

 5.1.2 案例

5.1.2.1 优化EmpMapper 新增一个方法update2

5.1.2.2 EmpMpapper.xml新增一个update2的sql 

5.1.2.3 新增测试方法testUpdate2测试

​编辑5.1.3 总结

5.2

5.2.1 优化EmpMapper 新增一个方法deleteByIds

5.2.2 EmpMpapper.xml新增一个deleteByIds的sql 

5.2.3 新增测试方法testDeleteByids

 5.2.4 总结

5.3

 5.3.1 EmpMpapper.xml新增sql 标签优化list2 include标签 

5.3.2 执行测试方法testList2

5.4 总结 


前言:Mybatis数据持久层,进行数据库操作,增删改查 ,动态sql

一 介绍

二 Mybatis的入门

2.1 快速入门

案例

 2.1.1 准备SpringBoot工程

 

2.1.2 创建数据库mybatis以及对应库表user

create database mybatis;
create table user(
     id int unsigned primary key auto_increment comment 'ID',
     name varchar(100) comment '姓名',
     age tinyint unsigned comment '年龄',
     gender tinyint unsigned comment '性别, 1:男, 2:女',
     phone varchar(11) comment '手机号'
) comment '用户表';

insert into user(id, name, age, gender, phone) VALUES (null,'白眉鹰王',55,'1','18800000000');
insert into user(id, name, age, gender, phone) VALUES (null,'金毛狮王',45,'1','18800000001');
insert into user(id, name, age, gender, phone) VALUES (null,'青翼蝠王',38,'1','18800000002');
insert into user(id, name, age, gender, phone) VALUES (null,'紫衫龙王',42,'2','18800000003');
insert into user(id, name, age, gender, phone) VALUES (null,'光明左使',37,'1','18800000004');
insert into user(id, name, age, gender, phone) VALUES (null,'光明右使',48,'1','18800000005');

2.1.3 创建User实体类

package com.runa.pojo;

public class User {
    private Integer id;
    private String name;
    private Short age;
    private Short gender;
    private String phone;

    public User() {
    }

    public User(Integer id, String name, Short age, Short gender, String phone) {
        this.id = id;
        this.name = name;
        this.age = age;
        this.gender = gender;
        this.phone = phone;
    }

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Short getAge() {
        return age;
    }

    public void setAge(Short age) {
        this.age = age;
    }

    public Short getGender() {
        return gender;
    }

    public void setGender(Short gender) {
        this.gender = gender;
    }

    public String getPhone() {
        return phone;
    }

    public void setPhone(String phone) {
        this.phone = phone;
    }

    @Override
    public String toString() {
        return "User{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", age=" + age +
                ", gender=" + gender +
                ", phone='" + phone + '\'' +
                '}';
    }
}

 2.1.4 配置application.properties数据库连接信息

# 配置数据库连接信息
#驱动类名称
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
#数据库连接的url
spring.datasource.url=jdbc:mysql://localhost:3306/mybatis
#连接数据库的用户名
spring.datasource.username=root
#连接数据库的密码
spring.datasource.password=1234
package com.runa.pojo;

public class User {

    private Integer id;
    private String name;
    private Short age;
    private Short gender;
    private String phone;

    public User(Integer id, String name, Short age, Short gender, String phone) {
        this.id = id;
        this.name = name;
        this.age = age;
        this.gender = gender;
        this.phone = phone;
    }

    public User() {
    }

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Short getAge() {
        return age;
    }

    public void setAge(Short age) {
        this.age = age;
    }

    public Short getGender() {
        return gender;
    }

    public void setGender(Short gender) {
        this.gender = gender;
    }

    public String getPhone() {
        return phone;
    }

    public void setPhone(String phone) {
        this.phone = phone;
    }

    @Override
    public String toString() {
        return "User{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", age=" + age +
                ", gender=" + gender +
                ", phone='" + phone + '\'' +
                '}';
    }
}

2.1.5 编写sql语句(注解方式)

package com.runa.mapper;

import com.runa.pojo.User;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Select;

import java.util.List;

@Mapper  // 运行时,会自动生成该接口的实现类对象(代理对象),并且将改对象交给IOC容器管理
public interface UserMapper {

    // 查询全部用户信息
    @Select("select * from user")
    public List<User> list();
}

2.1.6 测试运行 

package com.runa;

import com.runa.mapper.UserMapper;
import com.runa.pojo.User;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;

import java.util.List;

@SpringBootTest
class SpringbootMybatisQuickstartApplicationTests {

    @Autowired  // 注入
    private UserMapper userMapper;

    @Test
    public void testListUser() {
        List<User> userList = userMapper.list();
        userList.stream().forEach(user -> {
            System.out.println(user);
        });
    }


//    @Test
//    void contextLoads() {
//    }

}

 

 2.1.7 配置SQL提示

 设置好,还不行的话(删除其他数据库连接,刷新数据库连接),重启IEDA

2.2 JDBC介绍(了解)

2.2.1 JDBC 介绍


    @Test
    public void testJdbc() throws Exception {

        //1 注册驱动

        Class.forName("com.mysql.cj.jdbc.Driver");

        // 2 获取连接对象
        
        String url = "jdbc:mysql://localhost:3306/mybatis";
        String username = "root";
        String password = "runa#2050";
        Connection  connection = DriverManager.getConnection(url, username, password);

        // 3 获取执行sql的对象statement,执行sql 返回结果
        String sql = "select * from user";
        Statement statement = null;
        statement = connection.createStatement();

        ResultSet resultSet = null;
        resultSet = statement.executeQuery(sql);


        // 4 封装结果数据
        List<User> userList = new ArrayList<>();

        while (resultSet.next()) {

            int id = resultSet.getInt("id");
            String name = resultSet.getString("name");
            short age = resultSet.getShort("age");
            short gender = resultSet.getShort("gender");
            String phone = resultSet.getString("phone");

            User  user = new User(id, name, age, gender, phone);
            userList.add(user);

        }
        // 5 释放资源
        statement.close();
        connection.close();


        userList.stream().forEach(user -> {
            System.out.println(user);
        });
    }

 

 

2.2.2 jdbc与Mybatis对比

 

 

 

2.3 数据库连接池(了解)

2.3.1 概念

 

 

2.3.2 mybatis切换Druid(德鲁伊)连接池

 我没有配置成功

 2.3.3 总结

 

2.4 lombok

 

 

 添加依赖

    <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
        </dependency>

修改实体类User

package com.runa.pojo;

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

@Data
@NoArgsConstructor
@AllArgsConstructor
public class User {
    private Integer id;
    private String name;
    private Short age;
    private Short gender;
    private String phone;

}

 

三 Mybatis的基础操作

3.1 准备工作

 

 

3.1.1 数据脚本在mybatis表执行脚本

-- 部门管理
create table dept(
    id int unsigned primary key auto_increment comment '主键ID',
    name varchar(10) 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());



-- 员工管理
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 '密码',
  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());

3.1.2 创建一个springboot项目 

引入起步依赖mybatis、mysql驱动、lombok

3.1.3 application.properties配置

指定mybatis输出日志的位置。输出控制台

# 配置数据库连接
# 驱动类名称
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
# 连接数据库的url
spring.datasource.url=jdbc:mysql://localhost:3306/mybatis
#连接数据库用户名
spring.datasource.username=root
# 连接数据库密码
spring.datasource.password=runa#2050

# 指定mybatis输出日志的位置。输出控制台
mybatis.configuration.log-impl=org.apache.ibatis.logging.stdout.StdOutImpl

3.1.4 创建对应实体类Emp

package com.runa.pojo;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.time.LocalDate;
import java.time.LocalDateTime;

@Data
@NoArgsConstructor
@AllArgsConstructor
public class Emp {
    private Integer id;
    private String username;
    private String password;
    private String name;
    private Short gender;
    private String image;
    private Short job;
    private LocalDate entrydate;
    private Integer deptId;
    private LocalDateTime createTime;
    private LocalDateTime updateTime;
}

 

3.1.5 准备Mapper接口EmpMapper

 

package com.runa.mapper;

import org.apache.ibatis.annotations.Mapper;

@Mapper
public interface EmpMapper {
}

3.2 日志输出

3.2.1 性能高 

 

 

 3.2.2 更安全

 

 3.2.3 总结 使用#

 

 

3.3 删除

 

 3.3.1 EmpMapper接口添加 删除方法

package com.runa.mapper;

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

@Mapper
public interface EmpMapper {

    // 根据id删除数据
    @Delete("delete from emp where id = #{id}")
    public void delete(Integer id);
}

3.3.2 新增测试方法

package com.runa;

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

import java.sql.*;
import java.util.ArrayList;
import java.util.List;

@SpringBootTest
class SpringbootMybatisQuickstartApplicationTests {

    @Autowired //注入
    private EmpMapper empMapper;



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



}

改造一下获取返回值

package com.runa.mapper;

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

@Mapper
public interface EmpMapper {

    // 根据id删除数据
//    @Delete("delete from emp where id = #{id}")
//    public void delete(Integer id);

    // 根据id删除数据,并获取返回值
    @Delete("delete from emp where id = #{id}")
    public int delete(Integer id);
}
package com.runa;

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

import java.sql.*;
import java.util.ArrayList;
import java.util.List;

@SpringBootTest
class SpringbootMybatisQuickstartApplicationTests {

//    @Autowired  // 注入
//    private UserMapper userMapper;
    @Autowired //注入
    private EmpMapper empMapper;

//    @Test
//    public void testListUser() {
//        List<User> userList = userMapper.list();
//        userList.stream().forEach(user -> {
//            System.out.println(user);
//        });
//    }

//    @Test
//    public void testDelete(){
//        empMapper.delete(17);
//
//    }

    @Test  // 获取返回值
    public void testDelete(){
        int id = empMapper.delete(16);
        System.out.println(id);

    }


}

 

 

 返回 1表示删除成功,0 是失败

 

3.4 新增

 

3.4.1 EmpMapper接口添加 新增方法

package com.runa.mapper;

import com.runa.pojo.Emp;
import org.apache.ibatis.annotations.Delete;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Mapper;

@Mapper
public interface EmpMapper {

    // 根据id删除数据
    @Delete("delete from emp where id = #{id}")
    public void delete(Integer id);

    // 根据id删除数据,并获取返回值
//    @Delete("delete from emp where id = #{id}")
//    public int delete(Integer id);

    // 新增员工
    @Insert("insert into emp\n" +
            "(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.4.2 新增测试方法 

package com.runa;

import com.runa.mapper.EmpMapper;
import com.runa.mapper.UserMapper;
import com.runa.pojo.Emp;
import com.runa.pojo.User;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;

import java.sql.*;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

@SpringBootTest
class SpringbootMybatisQuickstartApplicationTests {

//    @Autowired  // 注入
//    private UserMapper userMapper;
    @Autowired //注入
    private EmpMapper empMapper;

//    @Test
//    public void testListUser() {
//        List<User> userList = userMapper.list();
//        userList.stream().forEach(user -> {
//            System.out.println(user);
//        });
//    }

    @Test
    public void testDelete(){
        empMapper.delete(17);

    }

//    @Test  // 获取返回值
//    public void testDelete(){
//        int id = empMapper.delete(16);
//        System.out.println(id);
//    }
    @Test
    public void testInsert(){
        // 构造员工对象
        Emp emp = new Emp();
        emp.setUsername("Bocai");
        emp.setName("菠菜");
        emp.setImage("1.jpg");
        emp.setGender((short)1);
        emp.setJob((short)1);
        emp.setEntrydate(LocalDate.of(2023, 2,27));
        emp.setCreateTime(LocalDateTime.now());
        emp.setUpdateTime(LocalDateTime.now());
        emp.setDeptId(1);

        // 执行新增员工的信息操作
        empMapper.insert(emp);
    }




}

 

 

3.4.3 主键返回

 

3.4.4 总结 

 

3.5 更新

 

3.5.1 EmpMapper接口添加 更新方法

package com.runa.mapper;

import com.runa.pojo.Emp;
import org.apache.ibatis.annotations.*;

@Mapper
public interface EmpMapper {

    // 根据id删除数据
    @Delete("delete from emp where id = #{id}")
    public void delete(Integer id);

    // 根据id删除数据,并获取返回值
//    @Delete("delete from emp where id = #{id}")
//    public int delete(Integer id);

    // 新增员工
    @Options(useGeneratedKeys = true, keyProperty = "id")
    @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);
 // 更新员工信息
    @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.5.2 新增测试方法

 

package com.runa;

import com.runa.mapper.EmpMapper;
import com.runa.mapper.UserMapper;
import com.runa.pojo.Emp;
import com.runa.pojo.User;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;

import java.sql.*;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

@SpringBootTest
class SpringbootMybatisQuickstartApplicationTests {

//    @Autowired  // 注入
//    private UserMapper userMapper;
    @Autowired //注入
    private EmpMapper empMapper;

//    @Test
//    public void testListUser() {
//        List<User> userList = userMapper.list();
//        userList.stream().forEach(user -> {
//            System.out.println(user);
//        });
//    }

    @Test
    public void testDelete(){
        empMapper.delete(17);

    }

//    @Test  // 获取返回值
//    public void testDelete(){
//        int id = empMapper.delete(16);
//        System.out.println(id);
//    }
    @Test
    public void testInsert(){
        // 构造员工对象
        Emp emp = new Emp();
        emp.setUsername("Bocai1");
        emp.setName("菠菜1");
        emp.setImage("1.jpg");
        emp.setGender((short)1);
        emp.setJob((short)1);
        emp.setEntrydate(LocalDate.of(2023, 2,27));
        emp.setCreateTime(LocalDateTime.now());
        emp.setUpdateTime(LocalDateTime.now());
        emp.setDeptId(1);

        // 执行新增员工的信息操作
        empMapper.insert(emp);
        System.out.println(emp.getId());
    }

    @Test
    public void testUpdate(){
        // 构造员工对象
        Emp emp = new Emp();
        emp.setId(19);
        emp.setUsername("Spring");
        emp.setName("春天的菠菜");
        emp.setImage("1.jpg");
        emp.setGender((short)1);
        emp.setJob((short)1);
        emp.setEntrydate(LocalDate.of(2023, 2,27));
        emp.setUpdateTime(LocalDateTime.now());
        emp.setDeptId(1);

        // 执行更新员工的信息操作
        empMapper.update(emp);

    }



}

3.6 查询

 

3.6.1 EmpMapper接口添加 查询方法

package com.runa.mapper;

import com.runa.pojo.Emp;
import org.apache.ibatis.annotations.*;

@Mapper
public interface EmpMapper {

    // 根据id删除数据
    @Delete("delete from emp where id = #{id}")
    public void delete(Integer id);

    // 根据id删除数据,并获取返回值
//    @Delete("delete from emp where id = #{id}")
//    public int delete(Integer id);

    // 新增员工
    @Options(useGeneratedKeys = true, keyProperty = "id")
    @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);

    // 更新员工信息
    @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);

    // 根据ID查询员工
    @Select("select * from emp where id = #{id}")
    public Emp getById(Integer id);


}

3.6.2 新增测试方法

package com.runa;

import com.runa.mapper.EmpMapper;
import com.runa.mapper.UserMapper;
import com.runa.pojo.Emp;
import com.runa.pojo.User;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;

import java.sql.*;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

@SpringBootTest
class SpringbootMybatisQuickstartApplicationTests {

//    @Autowired  // 注入
//    private UserMapper userMapper;
    @Autowired //注入
    private EmpMapper empMapper;

//    @Test
//    public void testListUser() {
//        List<User> userList = userMapper.list();
//        userList.stream().forEach(user -> {
//            System.out.println(user);
//        });
//    }

    @Test
    public void testDelete(){
        empMapper.delete(17);

    }

//    @Test  // 获取返回值
//    public void testDelete(){
//        int id = empMapper.delete(16);
//        System.out.println(id);
//    }

    // 测试新增
    @Test
    public void testInsert(){
        // 构造员工对象
        Emp emp = new Emp();
        emp.setUsername("Bocai1");
        emp.setName("菠菜1");
        emp.setImage("1.jpg");
        emp.setGender((short)1);
        emp.setJob((short)1);
        emp.setEntrydate(LocalDate.of(2023, 2,27));
        emp.setCreateTime(LocalDateTime.now());
        emp.setUpdateTime(LocalDateTime.now());
        emp.setDeptId(1);

        // 执行新增员工的信息操作
        empMapper.insert(emp);
        System.out.println(emp.getId());
    }

    // 测试更新
    @Test
    public void testUpdate(){
        // 构造员工对象
        Emp emp = new Emp();
        emp.setId(19);
        emp.setUsername("Spring");
        emp.setName("春天的菠菜");
        emp.setImage("1.jpg");
        emp.setGender((short)1);
        emp.setJob((short)1);
        emp.setEntrydate(LocalDate.of(2023, 2,27));
        emp.setUpdateTime(LocalDateTime.now());
        emp.setDeptId(1);

        // 执行更新员工的信息操作
        empMapper.update(emp);

    }

    // 根据员工ID查询员工
    @Test
    public void testGetById(){
        Emp emp = empMapper.getById(19);
        System.out.println(emp);
    }

}

 

3.6.3 数据封装

 3.6.3.1 方案一 (不推荐):当数据库字段与实体类字段不一致时取别名

 修改Empmapper接口类

    // 根据ID查询员工
//    @Select("select * from emp where id = #{id}")
//    public Emp getById(Integer id);

    // 根据ID查询员工,取别名方案
    @Select("select id,id, username, password, name, gender, image, job, entrydate, dept_id deptId, create_time createTime, update_time updateTime from emp where id = #{id}")
    public Emp getById(Integer id);

 

3.6.3.2 方案二(不推荐) :通过@Results, @Result注解手动映射封装

   // 根据ID查询员工
//    @Select("select * from emp where id = #{id}")
//    public Emp getById(Integer id);

    // 根据ID查询员工,方案一:取别名方案
//    @Select("select id,id, username, password, name, gender, image, job, entrydate, dept_id deptId, create_time createTime, update_time updateTime from emp where id = #{id}")
//    public Emp getById(Integer id);

    // 根据ID查询员工 方案二:通过@Results, @Result注解手动映射封装
    @Results({
            @Result(column = "dept_id", property = "deptId"),
            @Result(column = "create_time", property = "createTime"),
            @Result(column = "update_time", property = "updateTime")
    })
    @Select("select * from emp where id = #{id}")
    public Emp getById(Integer id);

 

 3.6.3.3 方案三(推荐):开启mybatis的驼峰命名自动映射开关

application.properties新增配置

# 配置数据库连接
# 驱动类名称
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
# 连接数据库的url
spring.datasource.url=jdbc:mysql://localhost:3306/mybatis
#连接数据库用户名
spring.datasource.username=root
# 连接数据库密码
spring.datasource.password=runa#2050

# 指定mybatis输出日志的位置。输出控制台
mybatis.configuration.log-impl=org.apache.ibatis.logging.stdout.StdOutImpl

# # 开启mybatis的驼峰命名自动映射开关
mybatis.configuration.map-underscore-to-camel-case=true

 

 

插曲:IDEA 的application.properties中文乱码,

配置前:

 修改后:

 

 

 

3.7 查询(条件查询)

 ​​​​​​​​​​​​​​

 

 

 

3.7.1 EmpMapper接口添加 条件查询方法

'%#{name}%' #{name}  不能出现在''里面所以改成$

package com.runa.mapper;

import com.runa.pojo.Emp;
import org.apache.ibatis.annotations.*;

import java.time.LocalDate;
import java.util.List;

@Mapper
public interface EmpMapper {

    // 根据id删除数据
    @Delete("delete from emp where id = #{id}")
    public void delete(Integer id);

    // 根据id删除数据,并获取返回值
//    @Delete("delete from emp where id = #{id}")
//    public int delete(Integer id);

    // 新增员工
    @Options(useGeneratedKeys = true, keyProperty = "id")
    @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);

    // 更新员工信息
    @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);

    // 根据ID查询员工
    @Select("select * from emp where id = #{id}")
    public Emp getById(Integer id);

    // 根据ID查询员工, (不推荐)方案一:取别名方案
//    @Select("select id,id, username, password, name, gender, image, job, entrydate, dept_id deptId, create_time createTime, update_time updateTime from emp where id = #{id}")
//    public Emp getById(Integer id);

    // 根据ID查询员工 (不推荐)方案二:通过@Results, @Result注解手动映射封装
//    @Results({
//            @Result(column = "dept_id", property = "deptId"),
//            @Result(column = "create_time", property = "createTime"),
//            @Result(column = "update_time", property = "updateTime")
//    })
//    @Select("select * from emp where id = #{id}")
//    public Emp getById(Integer id);

    // 条件查询员工  '%#{name}%' #{name}  不能出现在''里面所以改成$
    @Select("select * from emp where name like '%${name}%'and gender = #{gender} and entrydate between #{begin} and #{end} order by update_time desc ")
    public List<Emp> list(String name, Short gender, LocalDate begin, LocalDate end);


}

3.7.2 新增测试方法

 

package com.runa;

import com.runa.mapper.EmpMapper;
import com.runa.mapper.UserMapper;
import com.runa.pojo.Emp;
import com.runa.pojo.User;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;

import java.sql.*;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

@SpringBootTest
class SpringbootMybatisQuickstartApplicationTests {

//    @Autowired  // 注入
//    private UserMapper userMapper;
    @Autowired //注入
    private EmpMapper empMapper;

//    @Test
//    public void testListUser() {
//        List<User> userList = userMapper.list();
//        userList.stream().forEach(user -> {
//            System.out.println(user);
//        });
//    }

    @Test
    public void testDelete(){
        empMapper.delete(17);

    }

//    @Test  // 获取返回值
//    public void testDelete(){
//        int id = empMapper.delete(16);
//        System.out.println(id);
//    }

    // 测试新增
    @Test
    public void testInsert(){
        // 构造员工对象
        Emp emp = new Emp();
        emp.setUsername("Bocai1");
        emp.setName("菠菜1");
        emp.setImage("1.jpg");
        emp.setGender((short)1);
        emp.setJob((short)1);
        emp.setEntrydate(LocalDate.of(2023, 2,27));
        emp.setCreateTime(LocalDateTime.now());
        emp.setUpdateTime(LocalDateTime.now());
        emp.setDeptId(1);

        // 执行新增员工的信息操作
        empMapper.insert(emp);
        System.out.println(emp.getId());
    }

    // 测试更新
    @Test
    public void testUpdate(){
        // 构造员工对象
        Emp emp = new Emp();
        emp.setId(19);
        emp.setUsername("Spring");
        emp.setName("春天的菠菜");
        emp.setImage("1.jpg");
        emp.setGender((short)1);
        emp.setJob((short)1);
        emp.setEntrydate(LocalDate.of(2023, 2,27));
        emp.setUpdateTime(LocalDateTime.now());
        emp.setDeptId(1);

        // 执行更新员工的信息操作
        empMapper.update(emp);

    }

    // 根据员工ID查询员工
    @Test
    public void testGetById(){
        Emp emp = empMapper.getById(19);
        System.out.println(emp);
    }

    // 条件查询
    @Test
    public void testList(){
        List<Emp> listEmp = empMapper.list("张", (short) 1, LocalDate.of(2010, 1, 1), LocalDate.of(2020, 1, 1));
        System.out.println(listEmp);
    }



}

 

 3.7.3 使用concat解决使用'%$name}%'问题

修改EmpMapper接口

package com.runa.mapper;

import com.runa.pojo.Emp;
import org.apache.ibatis.annotations.*;

import java.time.LocalDate;
import java.util.List;

@Mapper
public interface EmpMapper {

    // 根据id删除数据
    @Delete("delete from emp where id = #{id}")
    public void delete(Integer id);

    // 根据id删除数据,并获取返回值
//    @Delete("delete from emp where id = #{id}")
//    public int delete(Integer id);

    // 新增员工
    @Options(useGeneratedKeys = true, keyProperty = "id")
    @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);

    // 更新员工信息
    @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);

    // 根据ID查询员工
    @Select("select * from emp where id = #{id}")
    public Emp getById(Integer id);

    // 根据ID查询员工, (不推荐)方案一:取别名方案
//    @Select("select id,id, username, password, name, gender, image, job, entrydate, dept_id deptId, create_time createTime, update_time updateTime from emp where id = #{id}")
//    public Emp getById(Integer id);

    // 根据ID查询员工 (不推荐)方案二:通过@Results, @Result注解手动映射封装
//    @Results({
//            @Result(column = "dept_id", property = "deptId"),
//            @Result(column = "create_time", property = "createTime"),
//            @Result(column = "update_time", property = "updateTime")
//    })
//    @Select("select * from emp where id = #{id}")
//    public Emp getById(Integer id);

    // 条件查询员工  '%#{name}%' #{name}  不能出现在''里面所以改成$
//    @Select("select * from emp where name like '%${name}%'and gender = #{gender} and entrydate between #{begin} and #{end} order by update_time desc ")
//    public List<Emp> list(String name, Short gender, LocalDate begin, LocalDate end);

    // 条件查询员工 使用concat解决 '%${name}%'
    @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(String name, Short gender, LocalDate begin, LocalDate end);

}

 以下图片可忽略

四 XML映射文件

4.1 XML映射规范

4.1.1 第一步: 

 

EmpMapper.xml文件如下: 

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper>
    
</mapper>

 4.1.2 第二步:

 

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.runa.mapper.EmpMapper">

</mapper>

4.1.3 第三步

resultType : 表示单条记录所封装的类型

 

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.runa.mapper.EmpMapper">
            <!--id EmpMapper 方法名   resultType : 表示单条记录所封装的类型  -->
    <select id="list2" resultType="com.runa.pojo.Emp">
        select * from emp where name like concat('%', #{name}, '%')and gender = #{gender} and entrydate between #{begin} and #{end} order by update_time desc
    </select>

</mapper>

4.1.4 验证

package com.runa;

import com.runa.mapper.EmpMapper;
import com.runa.mapper.UserMapper;
import com.runa.pojo.Emp;
import com.runa.pojo.User;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;

import java.sql.*;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

@SpringBootTest
class SpringbootMybatisQuickstartApplicationTests {

//    @Autowired  // 注入
//    private UserMapper userMapper;
    @Autowired //注入
    private EmpMapper empMapper;

//    @Test
//    public void testListUser() {
//        List<User> userList = userMapper.list();
//        userList.stream().forEach(user -> {
//            System.out.println(user);
//        });
//    }

    @Test
    public void testDelete(){
        empMapper.delete(17);

    }

//    @Test  // 获取返回值
//    public void testDelete(){
//        int id = empMapper.delete(16);
//        System.out.println(id);
//    }

    // 测试新增
    @Test
    public void testInsert(){
        // 构造员工对象
        Emp emp = new Emp();
        emp.setUsername("Bocai1");
        emp.setName("菠菜1");
        emp.setImage("1.jpg");
        emp.setGender((short)1);
        emp.setJob((short)1);
        emp.setEntrydate(LocalDate.of(2023, 2,27));
        emp.setCreateTime(LocalDateTime.now());
        emp.setUpdateTime(LocalDateTime.now());
        emp.setDeptId(1);

        // 执行新增员工的信息操作
        empMapper.insert(emp);
        System.out.println(emp.getId());
    }

    // 测试更新
    @Test
    public void testUpdate(){
        // 构造员工对象
        Emp emp = new Emp();
        emp.setId(19);
        emp.setUsername("Spring");
        emp.setName("春天的菠菜");
        emp.setImage("1.jpg");
        emp.setGender((short)1);
        emp.setJob((short)1);
        emp.setEntrydate(LocalDate.of(2023, 2,27));
        emp.setUpdateTime(LocalDateTime.now());
        emp.setDeptId(1);

        // 执行更新员工的信息操作
        empMapper.update(emp);

    }

    // 根据员工ID查询员工
    @Test
    public void testGetById(){
        Emp emp = empMapper.getById(19);
        System.out.println(emp);
    }

    // 条件查询
    @Test
    public void testList(){
        List<Emp> listEmp = empMapper.list("张", (short) 1, LocalDate.of(2010, 1, 1), LocalDate.of(2020, 1, 1));
        System.out.println(listEmp);
    }

    // 条件查询 使用xml
    @Test
    public void testList2(){
        List<Emp> listEmp = empMapper.list2("张", (short) 1, LocalDate.of(2010, 1, 1), LocalDate.of(2020, 1, 1));
        System.out.println(listEmp);
    }


}

 

 4.2 mybatisx插件

 快速定位

 

4.3 总结

 

 

五 Mybatis的动态SQL

5.1 <if>

5.1.1 优化EmpMapper.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.runa.mapper.EmpMapper">
            <!--id EmpMapper 方法名   resultType : 表示单条记录所封装的类型  -->
    <select id="list2" resultType="com.runa.pojo.Emp">
        select *
        from emp
        <where>
            <if test= "name != null">
            name like concat('%', #{name}, '%')
            </if>
            <if test= "gender != null">
            and gender = #{gender}
            </if>
            <if test= "begin != null and end != null">
            and entrydate between #{begin} and #{end}
            </if>
            order by update_time desc
        </where>
    </select>

</mapper>

 

 

 

 注意:<where></where> 会针对多条件查询过滤一些特有的and

 5.1.2 案例

 

 

5.1.2.1 优化EmpMapper 新增一个方法update2

package com.runa.mapper;

import com.runa.pojo.Emp;
import org.apache.ibatis.annotations.*;

import java.time.LocalDate;
import java.util.List;

@Mapper
public interface EmpMapper {

    // 根据id删除数据
    @Delete("delete from emp where id = #{id}")
    public void delete(Integer id);

    // 根据id删除数据,并获取返回值
//    @Delete("delete from emp where id = #{id}")
//    public int delete(Integer id);

    // 新增员工
    @Options(useGeneratedKeys = true, keyProperty = "id")
    @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);

    // 更新员工信息
    @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);

    // 根据ID查询员工
    @Select("select * from emp where id = #{id}")
    public Emp getById(Integer id);

    // 根据ID查询员工, (不推荐)方案一:取别名方案
//    @Select("select id,id, username, password, name, gender, image, job, entrydate, dept_id deptId, create_time createTime, update_time updateTime from emp where id = #{id}")
//    public Emp getById(Integer id);

    // 根据ID查询员工 (不推荐)方案二:通过@Results, @Result注解手动映射封装
//    @Results({
//            @Result(column = "dept_id", property = "deptId"),
//            @Result(column = "create_time", property = "createTime"),
//            @Result(column = "update_time", property = "updateTime")
//    })
//    @Select("select * from emp where id = #{id}")
//    public Emp getById(Integer id);

    // 条件查询员工  '%#{name}%' #{name}  不能出现在''里面所以改成$
//    @Select("select * from emp where name like '%${name}%'and gender = #{gender} and entrydate between #{begin} and #{end} order by update_time desc ")
//    public List<Emp> list(String name, Short gender, LocalDate begin, LocalDate end);

    // 条件查询员工 使用concat解决 '%${name}%'
    @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(String name, Short gender, LocalDate begin, LocalDate end);

    // 条件查询员工使用xml方式
    public List<Emp> list2(String name, Short gender, LocalDate begin, LocalDate end);


    // 更新员工信息使用xml方式 使用<if>,使用动态sql方式
    public void update2(Emp emp);

}

5.1.2.2 EmpMpapper.xml新增一个update2的sql 

这里也使用了<set></set>标签

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.runa.mapper.EmpMapper">
    <!--id EmpMapper 方法名   resultType : 表示单条记录所封装的类型  -->
    <select id="list2" resultType="com.runa.pojo.Emp">
        select *
        from emp
        <where>
            <if test="name != null">
                name like concat('%', #{name}, '%')
            </if>
            <if test="gender != null">
                and gender = #{gender}
            </if>
            <if test="begin != null and end != null">
                and entrydate between #{begin} and #{end}
            </if>
            order by update_time desc
        </where>
    </select>

    <!-- 动态更新员工-->
    <update id="update2">
        update emp 
        <set>
        <if test="username != null">username = #{username},</if>
        <if test="name != null">name= #{name},</if>
        <if test="gender != null">gender = #{gender},</if>
        <if test="image != null">image = #{image},</if>
        <if test="job != null">job = #{job},</if>
        <if test="entrydate != null">entrydate = #{entrydate},</if>
        <if test="deptId != null">dept_id = #{deptId},</if>
        <if test="updateTime != null">update_time = #{updateTime}</if>
        </set>
        where id=#{id}
    </update>

</mapper>

5.1.2.3 新增测试方法testUpdate2测试

package com.runa;

import com.runa.mapper.EmpMapper;
import com.runa.mapper.UserMapper;
import com.runa.pojo.Emp;
import com.runa.pojo.User;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;

import java.sql.*;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

@SpringBootTest
class SpringbootMybatisQuickstartApplicationTests {

//    @Autowired  // 注入
//    private UserMapper userMapper;
    @Autowired //注入
    private EmpMapper empMapper;

//    @Test
//    public void testListUser() {
//        List<User> userList = userMapper.list();
//        userList.stream().forEach(user -> {
//            System.out.println(user);
//        });
//    }

    @Test
    public void testDelete(){
        empMapper.delete(17);

    }

//    @Test  // 获取返回值
//    public void testDelete(){
//        int id = empMapper.delete(16);
//        System.out.println(id);
//    }

    // 测试新增
    @Test
    public void testInsert(){
        // 构造员工对象
        Emp emp = new Emp();
        emp.setUsername("Bocai1");
        emp.setName("菠菜1");
        emp.setImage("1.jpg");
        emp.setGender((short)1);
        emp.setJob((short)1);
        emp.setEntrydate(LocalDate.of(2023, 2,27));
        emp.setCreateTime(LocalDateTime.now());
        emp.setUpdateTime(LocalDateTime.now());
        emp.setDeptId(1);

        // 执行新增员工的信息操作
        empMapper.insert(emp);
        System.out.println(emp.getId());
    }

    // 测试更新
    @Test
    public void testUpdate(){
        // 构造员工对象
        Emp emp = new Emp();
        emp.setId(19);
        emp.setUsername("Spring");
        emp.setName("春天的菠菜");
        emp.setImage("1.jpg");
        emp.setGender((short)1);
        emp.setJob((short)1);
        emp.setEntrydate(LocalDate.of(2023, 2,27));
        emp.setUpdateTime(LocalDateTime.now());
        emp.setDeptId(1);

        // 执行更新员工的信息操作
        empMapper.update(emp);

    }

    // 根据员工ID查询员工
    @Test
    public void testGetById(){
        Emp emp = empMapper.getById(19);
        System.out.println(emp);
    }

    // 条件查询
    @Test
    public void testList(){
        List<Emp> listEmp = empMapper.list("张", (short) 1, LocalDate.of(2010, 1, 1), LocalDate.of(2020, 1, 1));
        System.out.println(listEmp);
    }

    // 条件查询 使用xml
    @Test
    public void testList2(){
//        List<Emp> listEmp = empMapper.list2("张", (short) 1, LocalDate.of(2010, 1, 1), LocalDate.of(2020, 1, 1));
        List<Emp> listEmp = empMapper.list2("张", (short) 1, null, null);

        System.out.println(listEmp);
    }


    // 测试更新,使用动态sql 更新id为18的员工username bocai2 更新为  name菠菜大哥 更新为 gender更新为 2
    @Test
    public void testUpdate2(){
        // 构造员工对象
        Emp emp = new Emp();
        emp.setId(18);
        emp.setUsername("bocai2");
        emp.setName("菠菜大哥");
        emp.setDeptId(2);
        emp.setUpdateTime(LocalDateTime.now());

        // 执行更新员工的信息操作
        empMapper.update2(emp);

    }



}

5.1.3 总结

 

5.2 <foreach>

5.2.1 优化EmpMapper 新增一个方法deleteByIds

package com.runa.mapper;

import com.runa.pojo.Emp;
import org.apache.ibatis.annotations.*;

import java.time.LocalDate;
import java.util.List;

@Mapper
public interface EmpMapper {

    // 根据id删除数据
    @Delete("delete from emp where id = #{id}")
    public void delete(Integer id);

    // 根据id删除数据,并获取返回值
//    @Delete("delete from emp where id = #{id}")
//    public int delete(Integer id);

    // 新增员工
    @Options(useGeneratedKeys = true, keyProperty = "id")
    @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);

    // 更新员工信息
    @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);

    // 根据ID查询员工
    @Select("select * from emp where id = #{id}")
    public Emp getById(Integer id);

    // 批量删除员工
    public void deleteByIds(List<Integer> ids);

    // 根据ID查询员工, (不推荐)方案一:取别名方案
//    @Select("select id,id, username, password, name, gender, image, job, entrydate, dept_id deptId, create_time createTime, update_time updateTime from emp where id = #{id}")
//    public Emp getById(Integer id);

    // 根据ID查询员工 (不推荐)方案二:通过@Results, @Result注解手动映射封装
//    @Results({
//            @Result(column = "dept_id", property = "deptId"),
//            @Result(column = "create_time", property = "createTime"),
//            @Result(column = "update_time", property = "updateTime")
//    })
//    @Select("select * from emp where id = #{id}")
//    public Emp getById(Integer id);

    // 条件查询员工  '%#{name}%' #{name}  不能出现在''里面所以改成$
//    @Select("select * from emp where name like '%${name}%'and gender = #{gender} and entrydate between #{begin} and #{end} order by update_time desc ")
//    public List<Emp> list(String name, Short gender, LocalDate begin, LocalDate end);

    // 条件查询员工 使用concat解决 '%${name}%'
    @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(String name, Short gender, LocalDate begin, LocalDate end);

    // 条件查询员工使用xml方式
    public List<Emp> list2(String name, Short gender, LocalDate begin, LocalDate end);


    // 更新员工信息使用xml方式 使用<if>,使用动态sql方式
    public void update2(Emp emp);

}

5.2.2 EmpMpapper.xml新增一个deleteByIds的sql 

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.runa.mapper.EmpMapper">

    <!--id EmpMapper 方法名   resultType : 表示单条记录所封装的类型  -->
    <select id="list2" resultType="com.runa.pojo.Emp">
        select *
        from emp
        <where>
            <if test="name != null">
                name like concat('%', #{name}, '%')
            </if>
            <if test="gender != null">
                and gender = #{gender}
            </if>
            <if test="begin != null and end != null">
                and entrydate between #{begin} and #{end}
            </if>
            order by update_time desc
        </where>
    </select>

    <!-- 动态更新员工-->
    <update id="update2">
        update emp
        <set>
        <if test="username != null">username = #{username},</if>
        <if test="name != null">name= #{name},</if>
        <if test="gender != null">gender = #{gender},</if>
        <if test="image != null">image = #{image},</if>
        <if test="job != null">job = #{job},</if>
        <if test="entrydate != null">entrydate = #{entrydate},</if>
        <if test="deptId != null">dept_id = #{deptId},</if>
        <if test="updateTime != null">update_time = #{updateTime}</if>
        </set>
        where id=#{id}
    </update>


        <!--    批量删除员工 (18,19,20)-->
    <!--
    collection : 要遍历的集合
    item : 遍历出来的元素
    separator : 分隔符
    open :遍历开始前拼接的sql片段
    close : 遍历结束后拼接的sql片段
    )-->
    <delete id="deleteByIds">
        delete from emp where id in
        <foreach collection="ids" item="id" separator="," open="(" close=")">
            #{id}
        </foreach>
    </delete>
</mapper>

5.2.3 新增测试方法testDeleteByids

 

package com.runa;

import com.runa.mapper.EmpMapper;
import com.runa.mapper.UserMapper;
import com.runa.pojo.Emp;
import com.runa.pojo.User;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;

import java.sql.*;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

@SpringBootTest
class SpringbootMybatisQuickstartApplicationTests {

//    @Autowired  // 注入
//    private UserMapper userMapper;
    @Autowired //注入
    private EmpMapper empMapper;

//    @Test
//    public void testListUser() {
//        List<User> userList = userMapper.list();
//        userList.stream().forEach(user -> {
//            System.out.println(user);
//        });
//    }

    @Test
    public void testDelete(){
        empMapper.delete(17);

    }

//    @Test  // 获取返回值
//    public void testDelete(){
//        int id = empMapper.delete(16);
//        System.out.println(id);
//    }

    // 测试新增
    @Test
    public void testInsert(){
        // 构造员工对象
        Emp emp = new Emp();
        emp.setUsername("Bocai1");
        emp.setName("菠菜1");
        emp.setImage("1.jpg");
        emp.setGender((short)1);
        emp.setJob((short)1);
        emp.setEntrydate(LocalDate.of(2023, 2,27));
        emp.setCreateTime(LocalDateTime.now());
        emp.setUpdateTime(LocalDateTime.now());
        emp.setDeptId(1);

        // 执行新增员工的信息操作
        empMapper.insert(emp);
        System.out.println(emp.getId());
    }

    // 测试更新
    @Test
    public void testUpdate(){
        // 构造员工对象
        Emp emp = new Emp();
        emp.setId(19);
        emp.setUsername("Spring");
        emp.setName("春天的菠菜");
        emp.setImage("1.jpg");
        emp.setGender((short)1);
        emp.setJob((short)1);
        emp.setEntrydate(LocalDate.of(2023, 2,27));
        emp.setUpdateTime(LocalDateTime.now());
        emp.setDeptId(1);

        // 执行更新员工的信息操作
        empMapper.update(emp);

    }

    // 根据员工ID查询员工
    @Test
    public void testGetById(){
        Emp emp = empMapper.getById(19);
        System.out.println(emp);
    }

    // 条件查询
    @Test
    public void testList(){
        List<Emp> listEmp = empMapper.list("张", (short) 1, LocalDate.of(2010, 1, 1), LocalDate.of(2020, 1, 1));
        System.out.println(listEmp);
    }

    // 条件查询 使用xml
    @Test
    public void testList2(){
//        List<Emp> listEmp = empMapper.list2("张", (short) 1, LocalDate.of(2010, 1, 1), LocalDate.of(2020, 1, 1));
        List<Emp> listEmp = empMapper.list2("张", (short) 1, null, null);

        System.out.println(listEmp);
    }


    // 测试更新,使用动态sql 更新id为18的员工username bocai2 更新为  name菠菜大哥 更新为 gender更新为 2
    @Test
    public void testUpdate2(){
        // 构造员工对象
        Emp emp = new Emp();
        emp.setId(18);
        emp.setUsername("bocai2");
        emp.setName("菠菜大哥");
        emp.setDeptId(2);
        emp.setUpdateTime(LocalDateTime.now());

        // 执行更新员工的信息操作
        empMapper.update2(emp);

    }

    // 批量删除员工 13 、 14、  15
    @Test
    public void testDeleteByids(){
        List<Integer> ids = Arrays.asList(13, 14, 15);
        empMapper.deleteByIds(ids);
    }



}

 

 

 

 5.2.4 总结

 

5.3 <sql><include>

存在大量重复的sql

解决方案

 

 

 5.3.1 EmpMpapper.xml新增sql 标签优化list2 include标签 

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.runa.mapper.EmpMapper">
    <sql id="commonSelect">
        select id,id, username, password, name, gender, image, job, entrydate, dept_id deptId, create_time createTime, update_time updateTime from emp
    </sql>
    <!--id EmpMapper 方法名   resultType : 表示单条记录所封装的类型  -->
    <select id="list2" resultType="com.runa.pojo.Emp">
        <include refid="commonSelect"></include>
        <where>
            <if test="name != null">
                name like concat('%', #{name}, '%')
            </if>
            <if test="gender != null">
                and gender = #{gender}
            </if>
            <if test="begin != null and end != null">
                and entrydate between #{begin} and #{end}
            </if>
            order by update_time desc
        </where>
    </select>

    <!-- 动态更新员工-->
    <update id="update2">
        update emp
        <set>
        <if test="username != null">username = #{username},</if>
        <if test="name != null">name= #{name},</if>
        <if test="gender != null">gender = #{gender},</if>
        <if test="image != null">image = #{image},</if>
        <if test="job != null">job = #{job},</if>
        <if test="entrydate != null">entrydate = #{entrydate},</if>
        <if test="deptId != null">dept_id = #{deptId},</if>
        <if test="updateTime != null">update_time = #{updateTime}</if>
        </set>
        where id=#{id}
    </update>


        <!--    批量删除员工 (18,19,20)-->
    <!--
    collection : 要遍历的集合
    item : 遍历出来的元素
    separator : 分隔符
    open :遍历开始前拼接的sql片段
    close : 遍历结束后拼接的sql片段
    )-->
    <delete id="deleteByIds">
        delete from emp where id in
        <foreach collection="ids" item="id" separator="," open="(" close=")">
            #{id}
        </foreach>
    </delete>
</mapper>

5.3.2 执行测试方法testList2

 

5.4 总结 

 

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

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

相关文章

Unity封装Debug.Log导致代码定位失准的解决办法

笔者通过翻资料&#xff0c;实现了这样的一个编辑器&#xff0c;虽然无法彻底消除指定的日志信息 但是可以实现”双击日志不跳转到这里的任意一个文件“ using System.Collections.Generic; using System.IO; using UnityEditor; using UnityEngine;namespace AirEditor {publ…

浅谈java自定义中类两个对象的比较

目录 实现比较两个对象是否相同 1.前置代码 1.学生类 2.示例 3.输出 4.原因 2.那么我们要怎么做呢? 1.对Student类中重新实现quals方法(即对equals方法重写) 2.完整代码如下: 3.具体操作 4.演示 1.示例 2.输出 3.原因 实现比较两个对象的大小 第一种: 用…

智慧小区建设方案【47页PPT】

导读&#xff1a;原文《智慧小区建设方案【47页PPT】》&#xff08;获取来源见文尾&#xff09;&#xff0c;本文精选其中精华及架构部分&#xff0c;逻辑清晰、内容完整&#xff0c;为快速形成售前方案提供参考。 部分页面&#xff1a; 喜欢文章&#xff0c;您可以关注评论转…

实现图片的动态连续展示 JAVA

目录 1、前言&#xff1a;2、图片的展示以及自动关闭&#xff1a;3、动画的连续展示&#xff1a; 1、前言&#xff1a; 要实现动画的流畅展示需要在能展示图片的基础上对图片进行关闭&#xff0c;再切换下一张图片&#xff0c;这要关闭窗口&#xff0c;与延时函数以及while函数…

从SVG到Canvas:选择最适合你的Web图形技术

SVG 和 Canvas 都是可以在 Web 浏览器中绘制图形的技术。 众所周知&#xff0c; icon 通常使用 svg&#xff08;如 iconfont&#xff09;&#xff0c;而交互式游戏采用 Canvas。二者具体的区别是什么&#xff1f;该如何选择&#xff1f; 声明式还是命令式&#xff1f;绘制的图形…

C语言:库函数atoi及其模拟实现

i&#xff1a; atof是C语言标准库中的一个函数&#xff0c;用于将字符串转换为对应的浮点数/整形数。 函数接受一个参数str&#xff0c;该参数是一个指向以null结尾的字符串的指针。atof函数会尝试将这个字符串转换为一个浮点数&#xff0c;并返回转换后的结果。 要注意的是&a…

【3D激光SLAM】LOAM源代码解析--laserOdometry.cpp

系列文章目录 【3D激光SLAM】LOAM源代码解析–scanRegistration.cpp 【3D激光SLAM】LOAM源代码解析–laserOdometry.cpp 写在前面 本系列文章将对LOAM源代码进行讲解&#xff0c;在讲解过程中&#xff0c;涉及到论文中提到的部分&#xff0c;会结合论文以及我自己的理解进行解…

Numpy入门(4)— 保存和导入文件

NumPy保存和导入文件 4.1 文件读写 NumPy可以方便的进行文件读写&#xff0c;如下面这种格式的文本文件&#xff1a; # 使用np.fromfile从文本文件a.data读入数据 # 这里要设置参数sep &#xff0c;表示使用空白字符来分隔数据 # 空格或者回车都属于空白字符&#xff0c;读…

leetcode 542. 01 Matrix(01矩阵)

矩阵中只有0&#xff0c;1值&#xff0c;返回每个cell到最近的0的距离。 思路&#xff1a; 0元素到它自己的距离是0&#xff0c; 只需考虑1到最近的0是多少距离。 BFS. 先把元素1处的距离更新为无穷大。 0的位置装入queue。 从每个0出发&#xff0c;走上下左右4个方向&…

Redis的8种数据结构和应用场景介绍,面试题答案

面试原题&#xff1a;你用过Redis哪些数据结构&#xff1f;&#xff08;网易一面 2023&#xff09;(面试题来自牛客网) 参考答案 后面有 详细答案解析&#xff0c;帮助更快记忆~ 参考答案共652字符&#xff0c;阅读约需1分8秒&#xff1b;全文共8694字符&#xff0c;阅读约需…

vscode打开nvue,vue3语法文件爆红

由于之前一直是用的vue2&#xff0c;也没用过nvue文件&#xff0c;这次下了hbulider的vue3云模板练手&#xff0c;图快直接在vscode的设置里的关联语言加上了 "files.associations": {// 文件关联语言的优先级配置"*.vue": "vue","*.nvue&…

解决多模块开发中的问题(聚合继承)

&#x1f40c;个人主页&#xff1a; &#x1f40c; 叶落闲庭 &#x1f4a8;我的专栏&#xff1a;&#x1f4a8; c语言 数据结构 javaweb 石可破也&#xff0c;而不可夺坚&#xff1b;丹可磨也&#xff0c;而不可夺赤。 Maven 一、聚合1.1创建Maven模块&#xff0c;设置打包类型…

特斯拉Cybertruck卡车实物照流出,今年 9月可交付?配置报价待定

根据最新的消息&#xff0c;特斯拉的Cybertruck目前正在冰岛的一座冰川上进行路测&#xff0c;并且据称特斯拉的团队还在利用这辆车拍摄相关的广告海报。这进一步表明特斯拉已经进入了Cybertruck的最后测试阶段&#xff0c;并且准备在今年9月底开始交付。然而&#xff0c;有外媒…

MyBatis的基本入门及Idea搭建MyBatis坏境且如何一步骤实现增删改查(CRUD)---详细介绍

一&#xff0c;MaBatis是什么&#xff1f; 首先是一个开源的Java持久化框架&#xff0c;它可以帮助开发人员简化数据库访问的过程并提供了一种将SQL语句与Java代码进行解耦的方式&#xff0c;使得开发人员可以更加灵活地进行数据库操作。 1.1 Mabatis 受欢迎的点 MyBatis不仅是…

使用 OpenTelemetry 构建可观测性 04 - 收集器

在之前的博文中&#xff0c;我们讨论了如何使用 SDK 和链路追踪生产者来导出进程中的遥测数据。尽管有多种类型的导出器可供选择&#xff0c;但其中一个常见的目标是将数据导出到 OpenTelemetry Collector。本篇文章将深入探讨收集器以及如何使用它。 选 OTel Collector 还是…

激活函数总结(十五):振荡系列激活函数补充(SQU、NCU、DSU、SSU)

激活函数总结&#xff08;十五&#xff09;&#xff1a;激活函数补充 1 引言2 激活函数2.1 Shifted Quadratic Unit (SQU) 激活函数2.2 Non-Monotonic Cubic Unit (NCU) 激活函数2.3 Decaying Sine Unit (DSU) 激活函数2.4 Shifted Sinc Unit (SSU) 激活函数 3. 总结 1 引言 在…

豪越科技受邀出席2023中国算力大会

2023年8月17日-8月20日&#xff0c;“算汇银川 数创未来”创新中国行走进银川暨2023中国算力大会在银川中关村创新中心召开。政府领导、行业领袖、专家学者、以及大型科技企业负责人齐聚大会现场&#xff0c;围绕算力基础设施建设、创新应用和产业发展成果等方面开展广泛交流与…

NSF拨款3800万美元让更多机构参与量子科学与工程

近日&#xff0c;美国国家科学基金会&#xff08;National Science Foundation&#xff0c;NSF&#xff09;宣布对“量子信息科学与工程扩展能力”&#xff08;Expanding Capacity in Quantum Information Science and Engineering&#xff0c;ExpandQISE&#xff09;计划拨款3…

好消息,微信又有免费提现活动了

​明天就是一年一度的七夕佳节&#xff0c;微信推出了「浪漫七夕&#xff0c;情寄明灯」活动&#xff0c;凡参与活动都可获得免费提现券等奖励。 01 活动时间 8 月 21 日 10 点至 8 月 24 日 24 点。 02 如何参与 活动入口&#xff1a; 在「微信支付有优惠」小程序专属入口…

解读2023年上半年财报:继续押注儿童业务的361°,有着怎样的野心?

“足球热”的风还是吹到了青少年身边&#xff0c;近日&#xff0c;济南历城二中女足问鼎2023世界中学生足球锦标赛女子组冠军&#xff0c;中国球队时隔16年再次获得世界中学生足球锦标赛冠军&#xff0c;点燃了不少足球爱好者的热情。 少儿体育热之下&#xff0c;与之相关的运…