NotesAtRandom——通用Mapper的使用方法

10/20 10:21
阅读数 30

写在前面:
  这段时间太忙了,已经一周没有更新了,抱歉抱歉。
  顺便多一嘴:这个其实还是学学思想,当成个工具就可以,在他之上还有个Mybatis-plus,这两个好用的工具都仅仅是工具,不能过度依赖。
  通用Mapper是国内的大神写的一个mybatis插件,里面有很多的增删改查方法,合理地(注意,一定要合理地)使用是可以优化代码。但是不能一味地为了不写而不写,这样的开发是没有意义的,借用原作者的一段话,希望大家可以明白:“通用 Mapper 的目的就是为了让开发人员能偷懒,能把更多的时间用在重要的事情上,但是有一部分人在不该偷懒的地方也偷懒了。”我个人也是非常赞同这个观点的,通用Mapper可以帮助我们去完成一些少量且繁琐的sql语句,所以,它只需要提供少量必要的通用方法就够了。


1 通用Mapper简介

  通用 Mapper4 是一个可以实现任意 MyBatis 通用方法的框架,项目提供了常规的增删改查操作以及Example 相关的单表操作。通用 Mapper 是为了解决MyBatis 使用中 90% 的基本操作,使用它可以很方便的进行开发,可以节省开发人员大量的时间。

  码云网址:通用Mapper

2 原生Mybatis的痛点

  既然前面已经说过通用Mapper的一些局限性了,那么在不考虑这个局限性的前提下,那这篇文章来说一下通用Mapper的优点:

  1. 原生的xml文件里主要就存放了我们大量的sql语句,如果出于特殊情况,数据库表字段发生了变动,那么xml就要进行Ctrl+R进行批量修改,并且再进行检查一下是否哪里修改出了点儿问题,任务太过繁重;
  2. 数据库如果发生了更替(也许这种情况不多,但是加入你在一个苦逼的外包公司,甲方今天说Oracle明天说MySQL,多烦躁),那么就需要修改大量的xml里的语句;
  3. 重复性的业务(增删改查A表、B表、C表…),我们出于习惯性,总是想着提出来一种方法进行复用,但是又没有办法去写这样一个工具类,不用怕,大佬给你准备好了😀😀😀。

3 快速构建

  既然这个工具类不是我写的,那我也就不多废话了,立刻上手教教大家如何入门,看完保证大家知道如果进行使用,但是一定要注意前面所说的合理地使用

3.1 创建数据库及表

① 创建数据库

CREATE DATABASE db_testCHARACTER SET utf8;

② 创建数据库表

USE db_test;
CREATE TABLE `t_user` (
	`id` BIGINT(20) NOT NULL AUTO_INCREMENT COMMENT '主键ID',
	`username` VARCHAR(20) NOT NULL COMMENT '用户名',
	`password` VARCHAR(20) NOT NULL COMMENT '密码',
	`name` VARCHAR(30) DEFAULT NULL COMMENT '姓名',
	`age` INT(11) DEFAULT NULL COMMENT '年龄',
	`telephone` VARCHAR(15) DEFAULT NULL COMMENT '手机号',
	`email` VARCHAR(50) DEFAULT NULL COMMENT '邮箱',
	PRIMARY KEY (`id`)
) ENGINE = INNODB AUTO_INCREMENT = 8 CHARSET = utf8;

INSERT INTO `t_user`
VALUES ('1', 'AAA', 'AAA111', '阿大', '25', '18211111111', 'NO.1@163.com');

INSERT INTO `t_user`
VALUES ('2', 'BBB', 'BBB222', '阿二', '24', '18222222222', 'NO.2@163.com');

INSERT INTO `t_user`
VALUES ('4', 'DDD', 'DDD444', '阿四', '22', '18244444444', 'NO.4@163.com');

INSERT INTO `t_user`
VALUES ('5', 'EEE', 'EEE555', '阿五', '21', '18255555555', 'NO.5@163.com');

INSERT INTO `t_user`
VALUES ('7', 'GGG', 'GGG777', '阿七', '19', '18277777777', 'NO.7@163.com');

原始表

这里指定一下自增从8开始,模拟数据库

3.2 工程搭建

① 创建SpringBoot工程

② pom.xml中导入依赖

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.1.4.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.g55zhw</groupId>
    <artifactId>mapperdemo</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>mapperdemo</name>
    <description>Demo project for Spring Boot</description>

    <properties>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter</artifactId>
            <!--排除spring-boot-starter-logging日志依赖,使用lf4j-log4j12日志依赖-->
            <exclusions>
                <exclusion>
                    <artifactId>spring-boot-starter-logging</artifactId>
                    <groupId>org.springframework.boot</groupId>
                </exclusion>
            </exclusions>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>

        <!--springboot整合通用mapper依赖-->
        <dependency>
            <groupId>tk.mybatis</groupId>
            <artifactId>mapper-spring-boot-starter</artifactId>
            <version>2.1.5</version>
        </dependency>

        <!--lombok依赖包-->
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>

        <!--mysql驱动-->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.47</version>
        </dependency>

        <!--lf4j-log4j12依赖,方便查询执行的sql语句-->
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-log4j12</artifactId>
        </dependency>

        <!--pageHelper依赖-->
        <dependency>
            <groupId>com.github.pagehelper</groupId>
            <artifactId>pagehelper-spring-boot-starter</artifactId>
            <version>1.2.10</version>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>
    
</project>

③ 配置外部文件

log4j.properties

log4j.rootLogger=DEBUG,A1
log4j.appender.A1=org.apache.log4j.ConsoleAppender
log4j.appender.A1.layout=org.apache.log4j.PatternLayout
log4j.appender.A1.layout.ConversionPattern=[%t] [%c]-[%p] %m%n

application.properties

# 设置应用的名称
spring.application.name = mapperdemo

#数据库驱动
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
#数据库访问路径
spring.datasource.url=jdbc:mysql://192.168.126.129/db_test
#使用Unicode字符集
useUnicode=true&characterEncoding=utf8&autoReconnect=true&allowMultiQueries=true&useSSL=false
#用户名
spring.datasource.username=root
#密码
spring.datasource.password=root

#pagehelper分页插件配置
pagehelper.helper-dialect=mysql
pagehelper.reasonable=true
pagehelper.support-methods-arguments=true
pagehelper.params=count=countSql

④ 编写pojo

package com.g55zhw.mapperdemo.pojo;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import tk.mybatis.mapper.annotation.KeySql;

import javax.persistence.Column;
import javax.persistence.Id;
import javax.persistence.Table;
// lombok : 简化实体类的编写,可以省略实体的构造函数、属性的set和get方法
// lombok用法:1.引入依赖;2.idea安装lombok插件;3.实体类中使用注解

/**
 * com.g55zhw.mapperdemo.pojo
 *
 * @author g55zhw
 * @create 2020-10-18-11-58
 */
@Data 					 //生成get/set方法
@NoArgsConstructor 		 //生成一个无参数的构造方法
@AllArgsConstructor 	 //生成一个包含所有变量的构造方法

@Table(name="t_user")
public class User {
   
   

    @Id 数据库表中的id主键和实体类id属性的映射关系
    @KeySql(useGeneratedKeys = true)//在增加数据之后,获取增加数据的id,填充到实体类id属性
    private Long id;
    @Column(name = "username") //实体类的userName属性,对应数据库表中的user_name字段
    private String userName;
    private String password;
    private String name;
    private Integer age;
    private String telephone;
    private String email;
}

⑤ 创建mapper接口

package com.g55zhw.mapperdemo.mapper;


import com.g55zhw.mapperdemo.pojo.User;
import tk.mybatis.mapper.common.Mapper;

/**
 * com.g55zhw.mapperdemo.pojo
 * 
 * mapper接口
 * 如果要实现基本的增、删、改、查等,需要继承BaseMapper
 * 如果要实现条件查询等,需要继承Mapper
 * 泛型表示mapper操作哪个实体类及实体类对应的表
 *
 * @author g55zhw
 * @create 2020-10-18-12-01
 */
public interface UserMapper extends Mapper<User> {
   
   
}

⑥ 创建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.g55zhw.mapperdemo.mapper.UserMapper">

</mapper>

⑦ 修改引导类,添加mapper包扫描

package com.g55zhw.mapperdemo;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import tk.mybatis.spring.annotation.MapperScan;

/**
 * com.g55zhw.mapperdemo.pojo
 * 
 * @author g55zhw
 * @create 2020-10-18-12-04
 */
@MapperScan("com.g55zhw.mapperdemo.mapper")
@SpringBootApplication
public class MapperdemoApplication {
   
   
    public static void main(String[] args) {
   
   
        SpringApplication.run(MapperdemoApplication.class, args);
    }
}

⑧ 单元测试框架

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import tk.mybatis.mapper.entity.Example;

import java.util.ArrayList;
import java.util.List;

/**
 * com.g55zhw.mapperdemo.pojo
 * 
 * @author g55zhw
 * @create 2020-10-18-12-08
 */

@RunWith(SpringRunner.class)
@SpringBootTest
public class MapperdemoApplicationTests {
   
   

    @Autowired
    private UserMapper userMapper;

	//根据id查询数据
    @Test
    public void contextLoads() {
   
   
    }

	//新增用户
    @Test
    public void insertTest() {
   
   
	}

	//更新用户	
    @Test
    public void updateTest() {
   
   
    }

	//删除用户
    @Test
    public void deleteTest() {
   
           
    }

	//根据主键查询用户
    @Test
    public void selectTest() {
   
           
    }

	//查询全部用户
    @Test
    public void selectAllTest() {
   
           
    }

	//条件查询
    @Test
    public void selectByTest() {
   
        
    }

	//分页查询
    @Test
    public void selectPageTest() {
   
   
    }
}

4 CRUD测试

4.1 插入操作

代码演示

    @Test
    public void insertTest() {
   
   
        User user = new User();
        user.setName("阿八");
        user.setAge(18);
        user.setEmail("NO.8@163.com");
        user.setTelephone("18288888888");
        user.setUserName("HHH");
        user.setPassword("HHH888");

        int result = userMapper.insert(user);
        System.out.println("result="+result);
    }

执行结果

[main] [com.g55zhw.mapperdemo.mapper.UserMapper.insert]-[DEBUG] ==>  Preparing: INSERT INTO t_user ( id,username,password,name,age,telephone,email ) VALUES( ?,?,?,?,?,?,? ) 

......

result=1

增

4.2 删除操作

代码演示

    @Test
    public void deleteTest() {
   
   
        int result = userMapper.deleteByPrimaryKey(11);
        System.out.println("result="+result);
    }

执行结果

[main] [com.g55zhw.mapperdemo.mapper.UserMapper.deleteByPrimaryKey]-[DEBUG] ==>  Preparing: DELETE FROM t_user WHERE id = ? 

......

result=0

删无

代码演示

    @Test
    public void deleteTest() {
   
   
        int result = userMapper.deleteByPrimaryKey(11);
        System.out.println("result="+result);
    }

执行结果

[main] [com.g55zhw.mapperdemo.mapper.UserMapper.deleteByPrimaryKey]-[DEBUG] ==>  Preparing: DELETE FROM t_user WHERE id = ? 

......

result=1

删有

4.3 更新操作

代码演示

@Test
    public void updateTest() {
   
   
        User user = new User();
        user.setId(2L);
        user.setName("阿二想做老大");
        user.setAge(25);

        //int result = userMapper.updateByPrimaryKey(user);
        //updateByPrimaryKeySelective会对字段进行判断再更新(如果为Null就忽略更新),如果你只想更新某一字段,可以用这个方法;
        //updateByPrimaryKey对你注入的字段全部更新
        int result = userMapper.updateByPrimaryKeySelective(user);
        System.out.println("result="+result);
    }

执行结果

[main] [com.g55zhw.mapperdemo.mapper.UserMapper.deleteByPrimaryKey]-[DEBUG] ==>  Preparing: DELETE FROM t_user WHERE id = ? 

......

result=1

更

4.4 查询操作

① 根据主键查询

代码演示

    @Test
    public void contextLoads() {
   
   
        User user = userMapper.selectByPrimaryKey(5);
        System.out.println(user);
    }

执行结果

[main] [com.g55zhw.mapperdemo.mapper.UserMapper.selectByPrimaryKey]-[DEBUG] ==>  Preparing: SELECT id,username,password,name,age,telephone,email FROM t_user WHERE id = ? 

......

User(id=5, userName=EEE, password=EEE555, name=阿五, age=21, telephone=18255555555, email=NO.5@163.com)

② 查询全部用户

代码演示

    @Test
    public void selectAllTest() {
   
   
        List<User> users = userMapper.selectAll();
        for (User user : users){
   
   
            System.out.println(user);
        }
    }

执行结果

[main] [com.g55zhw.mapperdemo.mapper.UserMapper.selectAll]-[DEBUG] ==>  Preparing: SELECT id,username,password,name,age,telephone,email FROM t_user 
[main] [com.g55zhw.mapperdemo.mapper.UserMapper.selectAll]-[DEBUG] ==> Parameters: 
[main] [com.g55zhw.mapperdemo.mapper.UserMapper.selectAll]-[DEBUG] <==      Total: 5

......

User(id=1, userName=AAA, password=AAA111, name=阿大, age=25, telephone=18211111111, email=NO.1@163.com)
User(id=2, userName=BBB, password=BBB222, name=阿二想做老大, age=25, telephone=18222222222, email=NO.2@163.com)
User(id=5, userName=EEE, password=EEE555, name=阿五, age=21, telephone=18255555555, email=NO.5@163.com)
User(id=7, userName=GGG, password=GGG777, name=阿七, age=19, telephone=18277777777, email=NO.7@163.com)
User(id=8, userName=HHH, password=HHH888, name=阿八, age=18, telephone=18288888888, email=NO.8@163.com)

③ 条件查询

代码演示

    @Test
    public void selectByTest() {
   
   
        Example example = new Example(User.class);
        Example.Criteria criteria = example.createCriteria();
        //查询“age”小于“20”的对象
        criteria.andLessThanOrEqualTo("age",20);
        List<User> users = userMapper.selectByExample(example);
        for (User user : users){
   
   
            System.out.println(user);
        }
    }

执行结果

[main] [com.g55zhw.mapperdemo.mapper.UserMapper.selectByExample]-[DEBUG] ==>  Preparing: SELECT id,username,password,name,age,telephone,email FROM t_user WHERE ( ( age <= ? ) ) 
[main] [com.g55zhw.mapperdemo.mapper.UserMapper.selectByExample]-[DEBUG] ==> Parameters: 20(Integer)
[main] [com.g55zhw.mapperdemo.mapper.UserMapper.selectByExample]-[DEBUG] <==      Total: 2

......

User(id=7, userName=GGG, password=GGG777, name=阿七, age=19, telephone=18277777777, email=NO.7@163.com)
User(id=8, userName=HHH, password=HHH888, name=阿八, age=18, telephone=18288888888, email=NO.8@163.com)

④ 分页查询

代码演示

    @Test
    @Test
    public void selectPageTest() {
   
   
        //显示示第一页,每页三条,按age升序
        PageHelper.startPage(1,3,"age asc");
        List<User> users = userMapper.selectAll();
        for (User user:users){
   
   
            System.out.println(user);
        }
    }

执行结果

[main] [com.g55zhw.mapperdemo.mapper.UserMapper.selectAll_COUNT]-[DEBUG] ==>  Preparing: SELECT count(0) FROM t_user 
[main] [com.g55zhw.mapperdemo.mapper.UserMapper.selectAll_COUNT]-[DEBUG] ==> Parameters: 
[main] [com.g55zhw.mapperdemo.mapper.UserMapper.selectAll_COUNT]-[DEBUG] <==      Total: 1
[main] [com.g55zhw.mapperdemo.mapper.UserMapper.selectAll]-[DEBUG] ==>  Preparing: SELECT id, username, password, name, age, telephone, email FROM t_user order by age asc LIMIT ? 
[main] [com.g55zhw.mapperdemo.mapper.UserMapper.selectAll]-[DEBUG] ==> Parameters: 3(Integer)
[main] [com.g55zhw.mapperdemo.mapper.UserMapper.selectAll]-[DEBUG] <==      Total: 3

......

User(id=8, userName=HHH, password=HHH888, name=阿八, age=18, telephone=18288888888, email=NO.8@163.com)
User(id=7, userName=GGG, password=GGG777, name=阿七, age=19, telephone=18277777777, email=NO.7@163.com)
User(id=5, userName=EEE, password=EEE555, name=阿五, age=21, telephone=18255555555, email=NO.5@163.com)
展开阅读全文
打赏
0
0 收藏
分享
加载中
更多评论
打赏
0 评论
0 收藏
0
分享
返回顶部
顶部