java

关注公众号 jb51net

关闭
首页 > 软件编程 > java > Mybatis-plus通用mapper

Mybatis-plus+通用mapper(tk.mybatis)的使用

作者:向岸看

本文主要介绍了Mybatis-plus+通用mapper(tk.mybatis)的使用,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧<BR>

01 引言

常规的MyBatis操作MySQL步骤

1>创建数据库,创建表

2>创建项目,导入逆向工程相对应的依赖与配置

3>逆向工程创建实体/mapper接口/mapper.xml映射文件

4>导入mybatis依赖,mysql依赖

5>编写测试类,测试mapper接口实现CRUD操作

问题:复杂项目Mybatis太过冗余。项目中,每张表对应一个实体类,对应一个mapper.java接口,也对应一个mapper.xml配置文件。每个mapper,java接口都有重复的增、删、改、查4个基础方法,每一个Mapper.xml都有重复的增、删、改、查4个基础sql语句。使用逆向工程可以解决,但是存在很致命的问题,如果列发生变动,对应的sql改动那就是灾难啦。另外,如果一个项目很复杂,那这些文件就膨胀起来,对项目的加载与维护带来很大挑战。此时不禁想,有没有某种方法可以不写crud方法,不写crud sql语句也能完成crud操作呢?

1)MyBatis与MyBatis-Plus区别

MyBatis:

优点

缺点

MyBatis-Plus 是在Mybatis的基础上进行二次开发的具有MyBatis所有功能,也添加了不少好用的功能

比如 :

2)Mybatis-plus入门案例

 案例一:spring容器版本的案例

1> sql导入:

CREATE TABLE `employee` (
  `id` bigint(20) NOT NULL AUTO_INCREMENT,
  `name` varchar(255) DEFAULT NULL,
  `password` varchar(255) DEFAULT NULL,
  `email` varchar(255) DEFAULT NULL,
  `age` int(11) DEFAULT NULL,
  `admin` bit(1) DEFAULT NULL,
  `dept_id` bigint(20) DEFAULT NULL,
  PRIMARY KEY (`id`) USING BTREE
) ENGINE=InnoDB DEFAULT CHARSET=utf8 ROW_FORMAT=DYNAMIC;
INSERT INTO `employee` VALUES (1, 'admin', '1', 'admin@abc.com', 40, b'1', 6);
INSERT INTO `employee` VALUES (2, '赵总', '1', 'zhaoz@langfeiyes.com', 35, b'0', 1);
INSERT INTO `employee` VALUES (3, '赵一明', '1', 'zhaoym@langfeiyes.com', 25, b'0', 1);
INSERT INTO `employee` VALUES (4, '钱总', '1', 'qianz@langfeiyes.com', 31, b'0', 2);
INSERT INTO `employee` VALUES (5, '钱二明', '1', 'qianem@langfeiyes.com', 25, b'0', 2);
INSERT INTO `employee` VALUES (6, '孙总', '1', 'sunz@langfeiyes.com', 35, b'0', 3);
INSERT INTO `employee` VALUES (7, '孙三明', '1', 'sunsm@langfeiyes.com', 25, b'0', 3);
INSERT INTO `employee` VALUES (8, '李总', '1', 'liz@langfeiyes.com', 35, b'0', 4);
INSERT INTO `employee` VALUES (9, '李四明', '1', 'lism@langfeiyes.com', 25, b'0', 4);
INSERT INTO `employee` VALUES (10, '周总', '1', 'zhouz@langfeiyes.com', 19, b'0', 5);
INSERT INTO `employee` VALUES (11, '周五明', '1', 'zhouwm@langfeiyes.com', 25, b'0', 5);
INSERT INTO `employee` VALUES (12, '吴总', '1', 'wuz@langfeiyes.com', 41, b'0', 5);
INSERT INTO `employee` VALUES (13, '吴六明', '1', 'wulm@langfeiyes.com', 33, b'0', 5);
INSERT INTO `employee` VALUES (14, '郑总', '1', 'zhengz@langfeiyes.com', 35, b'0', 3);
INSERT INTO `employee` VALUES (15, '郑七明', '1', 'zhengqm@langfeiyes.com', 25, b'0', 2);
INSERT INTO `employee` VALUES (16, '孙四明', '1', 'sunsim@langfeiyes.com', 25, b'0', 3);
INSERT INTO `employee` VALUES (17, '孙五明', '1', 'sunwm@langfeiyes.com', 25, b'0', 3);
INSERT INTO `employee` VALUES (18, '李五明', '1', 'liwm@langfeiyes.com', 25, b'0', 4);
INSERT INTO `employee` VALUES (19, '李六明', '1', 'lilm@langfeiyes.com', 25, b'0', 4);
INSERT INTO `employee` VALUES (20, '叶子', '1', 'yezi@langfeiyes.com', 0, b'0', 1);

2> 依赖引入:

<properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <maven.compiler.source>11</maven.compiler.source>
        <maven.compiler.target>11</maven.compiler.target>
    </properties>


    <dependencies>
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus</artifactId>
            <version>3.4.3.4</version>
        </dependency>

        <!--数据连接池依赖-->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>1.2.8</version>
        </dependency>

        <!--mysql驱动依赖-->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.22</version>
        </dependency>
        <!--自动生成getter/setter方法依赖-->
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.18.16</version>
            <scope>provided</scope>
        </dependency>
        <!--单元测试-->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
            <scope>test</scope>
        </dependency>
        <!--spring测试-->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-test</artifactId>
            <version>5.2.16.RELEASE</version>
        </dependency>

        <!--spring环境依赖包-->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>5.2.16.RELEASE</version>
        </dependency>
        <!--spring事务依赖包-->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-tx</artifactId>
            <version>5.2.16.RELEASE</version>
        </dependency>
        <!--spring jdbc依赖包-->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>5.2.16.RELEASE</version>
        </dependency>
        <!--spring 日志依赖包-->
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-log4j12</artifactId>
            <version>1.7.25</version>
        </dependency>
    </dependencies>

3> 配置数据db.properties、日志文件log4j.properties、spring容器文件spring-context-mybatis.xml

jdbc.url=jdbc:mysql://localhost:3306/mybatis-plus?useUnicode=true&characterEncoding=utf8&serverTimezone=GMT%2B8
jdbc.username=root
jdbc.password=123456
jdbc.driverClassName=com.mysql.cj.jdbc.Driver
# Global logging configuration
log4j.rootLogger=ERROR, stdout

# 设置 com.langfeiyes.mp.mapper 包下的日志级别为 TRACE,表示输出该包下所有类的 TRACE 级别的日志信息
log4j.logger.com.example.demo.mapper=TRACE
# Console output...
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%5p [%t] - %m%n
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:p="http://www.springframework.org/schema/p"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
       xmlns:util="http://www.springframework.org/schema/util"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
    http://www.springframework.org/schema/context
    http://www.springframework.org/schema/context/spring-context-3.0.xsd
    http://www.springframework.org/schema/util
    http://www.springframework.org/schema/util/spring-util-3.0.xsd">

    <!-- 加载配置属性文件 -->
    <context:property-placeholder location="classpath:db.properties" ignore-unresolvable="true" />
    <!-- 配置数据源 -->
    <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource" init-method="init" destroy-method="close">
        <property name="driverClassName" value="${jdbc.driverClassName}"></property>
        <property name="username" value="${jdbc.username}"></property>
        <property name="password" value="${jdbc.password}"></property>
        <property name="url" value="${jdbc.url}"></property>
    </bean>
    <!-- 配置SessionFactory -->
    <bean id="sqlSessionFactory" class="com.baomidou.mybatisplus.extension.spring.MybatisSqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource"/>
    </bean>
    <!-- MyBatis 动态扫描  -->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="basePackage" value="com.langfeiyes.mp.mapper"/>
    </bean>
</beans>

 3> 编写Employee实体类与mapper接口

Employee.java 

package com.example.demo.domain;

import lombok.Getter;
import lombok.Setter;
import lombok.ToString;

@Setter
@Getter
@ToString
public class Employee {
    private Long id;
    private String name;
    private String password;
    private String email;
    private int age;
    private int admin;
    private Long deptId;

    public Long getId() {
        return id;
    }

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

    public String getName() {
        return name;
    }

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

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public int getAge() {
        return age;
    }

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

    public int getAdmin() {
        return admin;
    }

    public void setAdmin(int admin) {
        this.admin = admin;
    }

    public Long getDeptId() {
        return deptId;
    }

    public void setDeptId(Long deptId) {
        this.deptId = deptId;
    }
}

 EmployeeMapper.java

package com.example.demo.mapper;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.example.demo.domain.Employee;

/**
 *
 * 持久层映射接口:mybatis-plus
 * mybatis-plus mapper接口自定义
 * 1:自定义一个接口, 继承BaseMapper
 * BaseMapper接口通常定义了对数据库表的基本 CRUD(Create, Read, Update, Delete)操作,以及其他常用的查询方法
 * 2:指定接口泛型:当前接口操作实体对象:Employee
 *
 */

public interface EmployeeMapper extends BaseMapper<Employee> {

}

4> 编写测试类

package com.example.demo;

import com.example.demo.domain.Employee;
import com.example.demo.mapper.EmployeeMapper;
import org.junit.jupiter.api.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;


@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration({"classpath:spring-context-mybatis.xml"})
public class MapperTest {
	@Autowired
	private EmployeeMapper employeeMapper;

	@Test
	public void testSave(){
		Employee employee = new Employee();
		employee.setAdmin(1);
		employee.setAge(18);
		employee.setDeptId(1L);
		employee.setEmail("yezi@langfeiyes.com");
		employee.setName("yezi");
		employee.setPassword("111");
		employeeMapper.insert(employee);
	}
	@Test
	public void testUpdate(){
		Employee employee = new Employee();
		employee.setId(1L);
		employee.setAdmin(1);
		employee.setAge(18);
		employee.setDeptId(1L);
		employee.setEmail("yezi@langfeiyes.com");
		employee.setName("yezi");
		employee.setPassword("111");
		employeeMapper.updateById(employee);
	}
	@Test
	public void testDelete(){
		employeeMapper.deleteById(1L);
	}
	@Test
	public void testGet(){
		System.out.println(employeeMapper.selectById(1L));
	}

	@Test
	public void testList(){
		System.out.println(employeeMapper.selectList(null));
	}
}

案例二:springboot 版本的案例

1> 导入依赖

<?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>3.2.4</version>
		<relativePath/> <!-- lookup parent from repository -->
	</parent>
	<groupId>com.example</groupId>
	<artifactId>mybatis-plus-demo</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<name>mybatis-plus-demo</name>
	<description>mybatis-plus-demo</description>
	<properties>
		<java.version>21</java.version>
	</properties>


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

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

		<dependency>
			<groupId>org.mybatis.spring.boot</groupId>
			<artifactId>mybatis-spring-boot-starter</artifactId>
			<version>3.0.3</version>
		</dependency>

		<!--mybatis-plus依赖-->
		<dependency>
			<groupId>com.baomidou</groupId>
			<artifactId>mybatis-plus-boot-starter</artifactId>
			<version>3.5.5</version>
		</dependency>

		<!--数据连接池依赖-->
		<dependency>
			<groupId>com.alibaba</groupId>
			<artifactId>druid-spring-boot-starter</artifactId>
			<version>1.1.17</version>
		</dependency>
		<!--mysql驱动依赖-->
		<dependency>
			<groupId>mysql</groupId>
			<artifactId>mysql-connector-java</artifactId>
			<version>8.0.22</version>
		</dependency>
		<!--测试依赖-->
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-test</artifactId>
		</dependency>
		<!--自动生成getter/setter方法依赖-->
		<dependency>
			<groupId>org.projectlombok</groupId>
			<artifactId>lombok</artifactId>
			<version>1.18.30</version>
			<scope>provided</scope>
		</dependency>

	</dependencies>

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

</project>

 2>  在application.properties文件中配置数据库连接四要素与日志

#mysql
spring.datasource.url=jdbc:mysql://localhost:3306/mybatis-plus?useUnicode=true&characterEncoding=utf8&serverTimezone=GMT%2B8
spring.datasource.username=root
spring.datasource.password=admin
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
 
# 配置sql打印日志
mybatis-plus.configuration.log-impl=org.apache.ibatis.logging.stdout.StdOutImpl

3> 编写Employee实体类与mapper接口(与上个案例一致)

4> 运行testList方法

(不知道,为什么出现中文乱码)

02 原理解析

两个问题: 

到此这篇关于Mybatis-plus+通用mapper(tk.mybatis)的使用的文章就介绍到这了,更多相关Mybatis-plus通用mapper内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家! 

您可能感兴趣的文章:
阅读全文