mybatis的快速入门以及spring boot整合mybatis(二)

2023-12-13 05:54:47

需要用到的SQL脚本:

CREATE TABLE dept (
  id int unsigned PRIMARY KEY AUTO_INCREMENT COMMENT 'ID, 主键',
  name varchar(10) NOT NULL UNIQUE COMMENT '部门名称',
  create_time datetime DEFAULT NULL COMMENT '创建时间',
  update_time datetime DEFAULT NULL COMMENT '修改时间'
) COMMENT '部门表';

INSERT INTO dept VALUES (1,'学工部','2023-09-25 09:47:40','2023-09-25 09:47:40'),
						  (2,'教研部','2023-09-25 09:47:40','2023-10-09 15:17:04'),
						  (3,'咨询部2','2023-09-25 09:47:40','2023-11-30 21:26:24'),
						  (4,'就业部','2023-09-25 09:47:40','2023-09-25 09:47:40'),
						  (5,'人事部','2023-09-25 09:47:40','2023-09-25 09:47:40'),
						  (15,'行政部','2023-11-30 20:56:37','2023-11-30 20:56:37');




create table emp(
    id int unsigned primary key auto_increment comment 'ID,主键',
    username varchar(20) not null unique comment '用户名',
    password varchar(50) default '123456' comment '密码',
    name varchar(10) not null comment '姓名',
    gender tinyint unsigned not null comment '性别, 1:男, 2:女',
    phone char(11) not null unique comment '手机号',
    job tinyint unsigned comment '职位, 1 班主任, 2 讲师 , 3 学工主管, 4 教研主管, 5 咨询师',
    salary int unsigned comment '薪资',
    image varchar(300) comment '头像',
    entry_date date comment '入职日期',
    dept_id int unsigned comment '部门ID',
    create_time datetime comment '创建时间',
    update_time datetime comment '修改时间'
) comment '员工表';


INSERT INTO emp VALUES 
(1,'shinaian','123456','施耐庵',1,'13309090001',4,15000,'5.png','2000-01-01',2,'2023-10-20 16:35:33','2023-11-16 16:11:26'),
(2,'songjiang','123456','宋江',1,'13309090002',2,8600,'01.png','2015-01-01',2,'2023-10-20 16:35:33','2023-10-20 16:35:37'),
(3,'lujunyi','123456','卢俊义',1,'13309090003',2,8900,'01.png','2008-05-01',2,'2023-10-20 16:35:33','2023-10-20 16:35:39'),
(4,'wuyong','123456','吴用',1,'13309090004',2,9200,'01.png','2007-01-01',2,'2023-10-20 16:35:33','2023-10-20 16:35:41'),
(5,'gongsunsheng','123456','公孙胜',1,'13309090005',2,9500,'01.png','2012-12-05',2,'2023-10-20 16:35:33','2023-10-20 16:35:43'),
(6,'huosanniang','123456','扈三娘',2,'13309090006',3,6500,'01.png','2013-09-05',1,'2023-10-20 16:35:33','2023-10-20 16:35:45'),
(7,'chaijin','123456','柴进',1,'13309090007',1,4700,'01.png','2005-08-01',1,'2023-10-20 16:35:33','2023-10-20 16:35:47'),
(8,'likui','123456','李逵',1,'13309090008',1,4800,'01.png','2014-11-09',1,'2023-10-20 16:35:33','2023-10-20 16:35:49'),
(9,'wusong','123456','武松',1,'13309090009',1,4900,'01.png','2011-03-11',1,'2023-10-20 16:35:33','2023-10-20 16:35:51'),
(10,'linchong','123456','林冲',1,'13309090010',1,5000,'01.png','2013-09-05',1,'2023-10-20 16:35:33','2023-10-20 16:35:53'),
(11,'huyanzhuo','123456','呼延灼',1,'13309090011',2,9700,'01.png','2007-02-01',2,'2023-10-20 16:35:33','2023-10-20 16:35:55'),
(12,'xiaoliguang','123456','小李广',1,'13309090012',2,10000,'01.png','2008-08-18',2,'2023-10-20 16:35:33','2023-10-20 16:35:57'),
(13,'yangzhi','123456','杨志',1,'13309090013',1,5300,'01.png','2012-11-01',1,'2023-10-20 16:35:33','2023-10-20 16:35:59'),
(14,'shijin','123456','史进',1,'13309090014',2,10600,'01.png','2002-08-01',2,'2023-10-20 16:35:33','2023-10-20 16:36:01'),
(15,'sunerniang','123456','孙二娘',2,'13309090015',2,10900,'01.png','2011-05-01',2,'2023-10-20 16:35:33','2023-10-20 16:36:03'),
(16,'luzhishen','123456','鲁智深',1,'13309090016',2,9600,'01.png','2010-01-01',2,'2023-10-20 16:35:33','2023-10-20 16:36:05'),
(17,'liying','12345678','李应',1,'13309090017',1,5800,'01.png','2015-03-21',1,'2023-10-20 16:35:33','2023-10-20 16:36:07'),
(18,'shiqian','123456','时迁',1,'13309090018',2,10200,'01.png','2015-01-01',2,'2023-10-20 16:35:33','2023-10-20 16:36:09'),
(19,'gudasao','123456','顾大嫂',2,'13309090019',2,10500,'01.png','2008-01-01',2,'2023-10-20 16:35:33','2023-10-20 16:36:11'),
(20,'ruanxiaoer','123456','阮小二',1,'13309090020',2,10800,'01.png','2018-01-01',2,'2023-10-20 16:35:33','2023-10-20 16:36:13'),
(21,'ruanxiaowu','123456','阮小五',1,'13309090021',5,5200,'01.png','2015-01-01',3,'2023-10-20 16:35:33','2023-10-20 16:36:15'),
(22,'ruanxiaoqi','123456','阮小七',1,'13309090022',5,5500,'01.png','2016-01-01',3,'2023-10-20 16:35:33','2023-10-20 16:36:17'),
(23,'ruanji','123456','阮籍',1,'13309090023',5,5800,'01.png','2012-01-01',3,'2023-10-20 16:35:33','2023-10-20 16:36:19'),
(24,'tongwei','123456','童威',1,'13309090024',5,5000,'01.png','2006-01-01',3,'2023-10-20 16:35:33','2023-10-20 16:36:21'),
(25,'tongmeng','123456','童猛',1,'13309090025',5,4800,'01.png','2002-01-01',3,'2023-10-20 16:35:33','2023-10-20 16:36:23'),
(26,'yanshun','123456','燕顺',1,'13309090026',5,5400,'01.png','2011-01-01',3,'2023-10-20 16:35:33','2023-11-08 22:12:46'),
(27,'lijun','123456','李俊',1,'13309090027',2,6600,'8.png','2004-01-01',2,'2023-10-20 16:35:33','2023-11-16 17:56:59'),
(28,'lizhong','123456','李忠',1,'13309090028',5,5000,'6.png','2007-01-01',3,'2023-10-20 16:35:33','2023-11-17 16:34:22'),
(30,'liyun','123456','李云',1,'13309090030',NULL,NULL,'01.png','2020-03-01',NULL,'2023-10-20 16:35:33','2023-10-20 16:36:31'),
(36,'linghuchong','123456','令狐冲',1,'18809091212',2,6800,'1.png','2023-10-19',2,'2023-10-20 20:44:54','2023-11-09 09:41:04');






员工列表查询:

基本查询:

需求:查询员工信息,并查询出部门名称。(涉及到的表:emp,dept)

基本查询的SQL语句:

select e.*, d.name deptName from emp e left join dept d on e.dept_id = d.id ;

?查询结果的封装,需要保证查询返回的字段名与类中的属性名保持一致。

在empController编写查询全部的方法,调用service层

?

    /**
     * 基本查询
     * @return
     */
    @GetMapping("/list")
    public Result getList(){
       List<Emp> empList =  empService.list();
        return Result.success(empList);
    }

编写 empService

  List<Emp> list();

编写empServiceImpl实现类:

    @Override
    public List<Emp> list() {
        return empMapper.getList();
    }

编写empMapper

?

    @Select("select e.*,d.name deptName from emp e left join dept d on e.dept_id = d.id")
    List<Emp> getList();

在Apifox里面测试:

分页查询:
原始的分页查询:

原始的分页查询会执行两条SQL语句

select * from emp e left join dept d on e.dept_id = d.id limit; 分页查询

select count(*)??from emp e left join dept d e.dept_id = d.id;? 查询数量

前端如何传递数据给后端:

当前页面:page

每页显示记录数: pageSize?

在empController编写方法:

    @GetMapping
    public Result list(Integer page,Integer pageSize){
        PageBean pageBean =  empService.getList(page,pageSize);
        return Result.success(pageBean);
    }

编写empService接口:

?

    /**
     * 分页查询
     * @param page
     * @param pageSize
     * @return
     */
    PageBean getList(Integer page, Integer pageSize);

编写empServiceImpl实现类:

    @Override
    public PageBean getList(Integer page, Integer pageSize) {
        //计算起始索引
        Integer start = (page - 1) * pageSize;
        //查询全部数据
        List<Emp> empList = empMapper.list(start,pageSize);
        //查询总的记录数
        Long count = empMapper.getCount();
        return new PageBean(count,empList);
    }

编写empMapper接口:

    @Select("select e.*,d.name deptName from emp e left join dept d on e.dept_id = d.id limit #{start},#{pageSize}")
    List<Emp> list(Integer start, Integer pageSize);

    @Select("select count(*) from emp left join dept on emp.dept_id = dept.id")
    Long getCount();

后端给前端返回的数据:

数据列表: List rows;

总记录数: Long total;

PageHelper分页插件:

PageHelper 是第三方提供的在mybatis框架中用来实现分页的插件,用来简化分页操作,提高开发效率。?

PageHelper实现机制:

?

使用步骤:
  • ?引入PageHelper的依赖
  • 定义Mapper接口的查询方法(无需考虑分页)
  • 在Service方法中实现分页查询?

引入依赖:

<!--        分页插件-->
        <dependency>
            <groupId>com.github.pagehelper</groupId>
            <artifactId>pagehelper-spring-boot-starter</artifactId>
            <version>1.4.7</version>
        </dependency>

?编写 EmpController层:

    @GetMapping
    public Result list(Integer page,Integer pageSize){
        PageBean pageBean =  empService.getList(page,pageSize);
        return Result.success(pageBean);
    }

编写EmpService接口:

?

    PageBean getList(Integer page, Integer pageSize);

编写 EmpServiceImpl实现类:

    /**
     * PageHeloer分页查询
     * @param page
     * @param pageSize
     * @return
     */
    @Override
    public PageBean getList(Integer page, Integer pageSize) {
        PageHelper.startPage(page,pageSize);
        List<Emp> empList = empMapper.PageList();
        Page<Emp> emps = (Page<Emp>) empList;
        return new PageBean(emps.getTotal(),emps.getResult());
    }

编写EmpMapper接口:

    /**
     * pageHelper分页查询
     */
    @Select("select e.*,d.name deptName from emp e left join dept d on e.dept_id = d.id ")
    List<Emp> PageList();

?调用Apifox测试:

控制台:

使用PageHelper分页插件的注意事项:
  • SQL语句结尾不要加分号(;)
  • PageHelper只会对紧跟在其后的第一条SQL语句进行分页处理

测试 在SQL语句结尾加分号(;)

    <select id="wherePage" resultType="com.sde.pojo.Emp">
        select e.*,d.name deptName from emp e left join dept d on e.dept_id = d.id
        <where>
            <if test="name != null and name != ''">
                e.name like concat('%',#{name},'%')
            </if>
            <if test="gender != null">
                and e.gender = #{gender}
            </if>
            <if test="begin != null and end != null">
                and e.entry_date between #{begin} and #{end}
            </if>
        </where>
        order by e.update_time desc;
    </select>

然后启动项目运行在Apifox测试:

?

控制台输出:

因为我们在后面加了分号,所以在最后执行 limit分页的时候,前面多了一个分号,所以SQL语句就报错了。

解决办法:去掉SQL语句后面最后面的一个分号(;)?

2,测试PageHelper之后执行,紧跟在后面的第一条SQL语句进行处理

?我把empMapper.PageList();方法复制一行写在下面,然后把它执行的SQL语句,强转成page,最后return出去。

在ApiFox里面测试:

?看看控制台:

条件分页查询:
  • select * from emp e ... where e.name like ?
  • select * from emp e ... where e.gender = ?
  • select * from emp e ... where e.name like ? and e.gender = ?

?接收请求参数:

接收条件分页查询的请求参数:GET /emps?name=张&gender=1&begin=2007-09-01&end=2022-09-01&page=1&pageSize=1

通过方法多形参,接收多参数:

就是前端在传递条件分页数据时,有多少参数就,在这个方法里面定义多少形参。

编写 EmpController

    /**
     * 条件分页查询--多参数接收
     * @param
     * @param
     * @return
     */
    @GetMapping("/getByList")
    public Result list(String name,Integer gender,
                       @DateTimeFormat(pattern = "yyyy-MM-dd") LocalDate begin,
                       @DateTimeFormat(pattern = "yyyy-MM-dd")  LocalDate end,
                       @RequestParam(defaultValue = "1") Integer page,
                       @RequestParam(defaultValue = "10") Integer pageSize){
        log.info("接收到前端传递来的参数:{},{},{},{},{},{}",name,gender,begin,end,page,pageSize);
       PageBean pageBean =  empService.moreQuery(name,gender,begin,end,page,pageSize);
      return Result.success(pageBean);
    }

编写EmpService接口:

PageBean moreQuery(String name, Integer gender, LocalDate begin, LocalDate end, Integer page, Integer pageSize);

编写 EmpServiceImpl实现类:

    @Override
    public PageBean moreQuery(String name, Integer gender, LocalDate begin, LocalDate end, Integer page, Integer pageSize) {
        PageHelper.startPage(page,pageSize);
       List<Emp> empList =  empMapper.getByWhere(name,gender,begin,end);
       Page p = (Page) empList;
        return new PageBean(p.getTotal(),p.getResult());
    }

编写 EmpMapper接口:

  List<Emp> getByWhere(String name, Integer gender, LocalDate begin, LocalDate end);

EmpMapper.xml配置文件:

在Apifox里面测试:

场景:如果参数个数比较少,建议直接接收即可。 如果参数个数较多,不便于维护和管理

在Controller方法中,通过实体对象接收。

在Controller方法中通过实体对象封装多个参数。(实体属性与请求参数名保持一致)

前端的请求:

GET /emps?name=张&gender=1&begin=2007-09-01&end=2022-09-01&page=1&pageSize=10

?定义一个 EmpQuery的实体类:

@Data
public class EmpQuery {
    private String name;
    private Integer gender;
    @DateTimeFormat(pattern = "yyyy-MM-dd")
    private LocalDate begin;
    @DateTimeFormat(pattern = "yyyy-MM-dd")
    private LocalDate end;
    private Integer page = 1;
    private Integer pageSize = 10;
}

编写 EmpController

/**
 * 条件分页查询用对象接收
 * @param empQuery
 * @return
 */
@GetMapping
public Result listQuery(EmpQuery empQuery){
    log.info("接收到前端传递来的参数:{}",empQuery);
   PageBean pageBean =  empService.wherePage(empQuery);
    return Result.success(pageBean);
}

编写EmpService接口:

    /**
     * 条件分页查询
     * @param empQuery
     * @return
     */
    PageBean wherePage(EmpQuery empQuery);

EmpServiceImpl实现类:

    /**
     * 条件分页查询
     * @param empQuery
     * @return
     */
    @Override
    public PageBean wherePage(EmpQuery empQuery) {
        //设置分压查询的参数
        PageHelper.startPage(empQuery.getPage(), empQuery.getPageSize());
        // 调用mapper接口,进行条件查询
       List<Emp> empList =  empMapper.wherePage(empQuery);
       //强转为page类型
        Page<Emp> page = (Page<Emp>) empList;
        return new PageBean(page.getTotal(),page.getResult());
    }

编写 EmpMapper接口:

    /**
     * 条件分页查询
     * @param empQuery
     * @return
     */
    List<Emp> wherePage(EmpQuery empQuery);

EmpMapper.xml配置文件:

    <select id="getByWhere" resultType="com.sde.pojo.Emp">
        select e.*,d.name deptName from emp e left join dept d on e.dept_id = d.id
        <where>
            <if test="name != null and name != ''">
                e.name like concat('%',#{name},'%')
            </if>
            <if test="gender != null">
                and e.gender = #{gender}
            </if>
            <if test="begin != bull and end != null ">
                and e.entry_date between #{begin} and #{end}
            </if>
        </where>
    </select>

在Apifox里面测试:

接收时间日期的参数:

@LocalDateTime 这个注解,有一个pattern属性,可以指定接收前端的数据格式。

@LocalDateTime(pattern="yyyy-MM-dd")

where 标签的作用:
  • 自动根据条件判定是否添加 where 关键字
  • 可以去除掉第一个前面多余的and或or

文章来源:https://blog.csdn.net/weixin_64502989/article/details/134891471
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。