MyBatis-Plus之面向Mapper编程

Posted 程序猿老高

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了MyBatis-Plus之面向Mapper编程相关的知识,希望对你有一定的参考价值。

MyBatis-Plus(简称 MP)是一个 MyBatis 的增强工具,在 MyBatis 的基础上只做增强不做改变,为简化开发、提高效率而生。

官网:https://mp.baomidou.com/

MyBatis-Plus技术提供了面向Service和面向Mapper两种编程途径,这里给大家介绍一下如何使用Mapper实现数据增删改查和分页:

1、表与数据
CREATE TABLE `student` (
  `sno` int PRIMARY KEY AUTO_INCREMENT,
  `sname` varchar(255) NOT NULL,
  `ssex` varchar(1) CHARACTER SET utf8 COLLATE utf8_general_ci DEFAULT '1',
  `birthday` timestamp(6) NULL DEFAULT NULL,
  `pass` varchar(255) DEFAULT NULL,
  `mno` int DEFAULT NULL,
  `delFlg` int DEFAULT '1' COMMENT '1:不删除;0:删除状态'
)

INSERT INTO `student` VALUES (1, 'Tom', '1', '2020-07-31 00:00:00.000000', '111111', 1, 0);
INSERT INTO `student` VALUES (2, 'Jack', '1', '2020-07-31 00:00:00.000000', '111111', 2, 0);
INSERT INTO `student` VALUES (3, '张三', '1', '2020-08-03 09:06:38.000000', '111111', 5, 1);
INSERT INTO `student` VALUES (4, '张伟', '1', '2020-08-03 09:06:38.000000', '111111', 6, 1);
2、Maven依赖
<dependency>
	<groupId>org.springframework</groupId>
	<artifactId>spring-context</artifactId>
	<version>5.3.9</version>
</dependency>
<dependency>
	<groupId>org.springframework</groupId>
	<artifactId>spring-jdbc</artifactId>
	<version>5.3.9</version>
</dependency>
<dependency>
	<groupId>com.zaxxer</groupId>
	<artifactId>HikariCP</artifactId>
	<version>3.4.5</version>
</dependency>
<dependency>
	<groupId>mysql</groupId>
	<artifactId>mysql-connector-java</artifactId>
	<version>8.0.30</version>
</dependency>
<dependency>
	<groupId>com.baomidou</groupId>
	<artifactId>mybatis-plus</artifactId>
	<version>3.4.1</version>
</dependency>
<dependency>
	<groupId>org.slf4j</groupId>
	<artifactId>slf4j-log4j12</artifactId>
	<version>1.6.4</version>
</dependency>
3、Log4j配置
log4j.rootLogger=debug,console,file

#输出到控制台
log4j.appender.console=org.apache.log4j.ConsoleAppender
log4j.appender.console.layout=org.apache.log4j.PatternLayout
log4j.appender.console.layout.ConversionPattern=%-5p %dMM-dd HH:mm:ss,SSS %m  (%F:%L) \\n

#输出到文件
log4j.appender.file=org.apache.log4j.FileAppender
log4j.appender.file.File=D:\\\\log4j.log
log4j.appender.file.layout=org.apache.log4j.PatternLayout
log4j.appender.file.layout.ConversionPattern=%-5p %dMM-dd HH:mm:ss,SSS %m  (%F:%L) \\n

#SQL语句
log4j.logger.com.mybatis=DEBUG
log4j.logger.com.mybatis.common.jdbc.SimpleDataSource=DEBUG
log4j.logger.com.mybatis.common.jdbc.ScriptRunner=DEBUG
log4j.logger.com.mybatis.sqlmap.engine.impl.SqlMapClientDelegate=DEBUG
log4j.logger.java.sql.Connection=DEBUG
log4j.logger.java.sql.Statement=DEBUG
log4j.logger.java.sql.PreparedStatement=DEBUG
4、MyBatis全局配置
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
</configuration>
5、Spring配置
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:mybatis-spring="http://mybatis.org/schema/mybatis-spring"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
        https://www.springframework.org/schema/beans/spring-beans.xsd http://mybatis.org/schema/mybatis-spring http://mybatis.org/schema/mybatis-spring.xsd">

    <!--数据源配置-->
    <bean id="dataSource" class="com.zaxxer.hikari.HikariDataSource" lazy-init="false" destroy-method="close">
        <property name="driverClassName" value="com.mysql.cj.jdbc.Driver"></property>
        <property name="jdbcUrl" value="jdbc:mysql://127.0.0.1:3306/test?characterEncoding=utf8"></property>
        <property name="username" value="root"></property>
        <property name="password" value="root"></property>
    </bean>

    <!--MyBatis配置-->
    <bean class="com.baomidou.mybatisplus.extension.spring.MybatisSqlSessionFactoryBean">
        <!--数据源注入-->
        <property name="dataSource" ref="dataSource"/>
        <!--加载MyBatis配置文件-->
        <property name="configLocation" value="mybatis-config.xml"/>
        <!--插件-->
        <property name="plugins">
            <!--PageHelper-->
            <!--<bean class="com.github.pagehelper.PageInterceptor"></bean>-->
            <!--MyBatisPlus分页插件-->
            <bean class="com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor">
                <property name="interceptors">
                    <list>
                        <bean class="com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor">
                            <!--数据库类型-->
                            <constructor-arg name="dbType" value="MYSQL"></constructor-arg>
                        </bean>
                    </list>
                </property>
            </bean>
        </property>
    </bean>

    <!--接口扫描-->
    <mybatis-spring:scan base-package="com.soft.*.dao"></mybatis-spring:scan>
</beans>
6、实体类
public class Student 
    @TableId(value="sno", type = IdType.AUTO)
    private String sno;
    private String sname;
    private String ssex;
    private String birthday;
    private String pass;
    private String mno;
    @TableField("delFlg")
    private String delFlg;//默认情况下,MyBatisPlus会将驼峰命名的变量变为下划线间隔的字段,除非使用TableField注解手动指定字段名
    
    // 省略set/get方法  

7、Dao接口
package com.soft.student.dao;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.soft.vo.Student;

public interface IStudentDao extends BaseMapper<Student> 

8、测试
8.1、增
package com.soft.test;

import com.soft.student.dao.IStudentDao;
import com.soft.vo.Student;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class InsertTest 

    public static void main(String[] args) 
        ClassPathXmlApplicationContext applicationContext = new ClassPathXmlApplicationContext("application.xml");
        IStudentDao studentDao = applicationContext.getBean(IStudentDao.class);
        //添加(主键自增,在实体类上加上@TableId既可以  @TableId(value = "id", type = IdType.AUTO))
        Student student = new Student();
        student.setSname("高焕杰");
        student.setSsex("1");
        student.setBirthday("2022-06-08");
        student.setPass("123456");
        student.setMno("5");
        student.setDelFlg("1");
        int rusult = studentDao.insert(student);
        System.out.println(rusult);
    

8.2、删
package com.soft.test;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.soft.student.dao.IStudentDao;
import com.soft.vo.Student;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

public class DeleteTest 

    public static void main(String[] args) 
        ClassPathXmlApplicationContext applicationContext = new ClassPathXmlApplicationContext("application.xml");
        IStudentDao studentDao = applicationContext.getBean(IStudentDao.class);

        //根据主键ID删除
        result = studentDao.deleteById(10);
        System.out.println("result = " + result);
        
        System.out.println("@@@@@@@@@@@@@@@@@");
        //根据id集合批量删除
        result = studentDao.deleteBatchIds(Arrays.asList(4,5));//idList 主键ID列表(不能为 null 以及 empty)
        System.out.println("result = " + result);
        
        System.out.println("@@@@@@@@@@@@@@@@@");
        //根据 entity 条件,删除记录
        Student student = new Student();
        student.setSname("张三");
        student.setSsex("1");
        //将实体对象进行包装,包装为操作条件
        QueryWrapper<Student> wrapper = new QueryWrapper<>(student);
        int result = studentDao.delete(wrapper);
        System.out.println("result = " + result);

        System.out.println("@@@@@@@@@@@@@@@@@");
        //根据条件模糊删除
        QueryWrapper<Student> wrapper = new QueryWrapper<>();
        wrapper.like("sname","四");
        result = studentDao.delete(wrapper);
        System.out.println(result);

        System.out.println("@@@@@@@@@@@@@@@@@");
        //根据 columnMap 条件,删除记录
        Map<String, Object> columnMap = new HashMap<>();
        columnMap.put("sname","张飞");
        columnMap.put("ssex","1");
        //将columnMap中的元素设置为删除的条件,多个之间为and关系
        result = studentDao.deleteByMap(columnMap);
        System.out.println("result = " + result);
    

8.3、改
package com.soft.test;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.soft.student.dao.IStudentDao;
import com.soft.vo.Student;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class UpdateTest 

    public static void main(String[] args) 
        ClassPathXmlApplicationContext applicationContext = new ClassPathXmlApplicationContext("application.xml");
        IStudentDao studentDao = applicationContext.getBean(IStudentDao.class);

        //根据 ID 修改
        Student student = new Student();
        student.setSno("6");//主键
        student.setSname("狗蛋儿");//更新的字段
        //根据id更新,更新不为null的字段
        studentDao.updateById(student);

        System.out.println("##################");
        //更新字段
        student = new Student();
        student.setSname("张老三");
        //更新条件
        QueryWrapper<Student> queryWrapper = new QueryWrapper<Student>();
        queryWrapper.eq("sno", 8);
        //更新操作
        int result = studentDao.update(student, queryWrapper);
        System.out.println("result = " + result);

        System.out.println("##################");
        //更新条件及字段
        UpdateWrapper<Student> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("sno", 11).set("sname", "李老四");
        //更新操作
        result = studentDao.update(null, updateWrapper);
        System.out.println("result = " + result);
    

8.4、查
package com.soft.test;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.soft.studentMybatis-plus异常解决之--org.apache.ibatis.binding.BindingException

Mybatis-Plus通用Mapper CRUD之insert(附带视频教程)

基于Spring+SpringMVC+MyBatis-Plus开发书评网图书详情模块开发之获取图书信息并展示

记录mybatis-plus多数据源批量操作时,数据源切换失效之谜

MyBatis-Plus

MyBatis-Plus 基础