整合MybatisPlus
简介
MyBatis-Plus(简称 MP)是一个 MyBatis的增强工具,在 MyBatis 的基础上只做增强不做改变,为简化开发、提高效率而生。
官网
创建项目工程
搭建环境并测试
系统要求
Java 8+
Maven 3.6.6 +
SpringBoot2.5+
引入 pom.xml 依赖
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.4.2</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<excludes>
<exclude>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</exclude>
</excludes>
</configuration>
</plugin>
</plugins>
</build>
编写sql
-- 创建数据库
create
database webapp1 charset utf8mb4;
-- 创建用户名、密码
create
user'webapp1'@'localhost'identified by'webapp1';
-- 授权
grant all
on webapp1.*to'webapp1'@'localhost';
-- 用用户名、密码登录
mysql -uwebapp1 -pwebapp1
-- 创建表
SET NAMES utf8mb4;
SET
FOREIGN_KEY_CHECKS = 0;
-- ----------------------------
-- Table structure for user
-- ----------------------------
DROP TABLE IF EXISTS `user`;
CREATE TABLE `user`
(
`id` int NOT NULL AUTO_INCREMENT,
`username` varchar(12) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL,
`sex` varchar(2) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL,
`age` int NULL DEFAULT NULL,
`birthday` date NULL DEFAULT NULL,
PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 554 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_0900_ai_ci ROW_FORMAT = Dynamic;
配置application.yml
spring:
datasource:
url: jdbc:mysql://localhost:3307/webapp1
username: webapp1
password: webapp1
driver-class-name: com.mysql.cj.jdbc.Driver
#mybatis日志:添加后可以查看执行的sql语句
mybatis-plus:
configuration:
log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
创建User类
package com.xiang.pojo;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.util.Date;
/**
* Created by IntelliJ IDEA.
* User: xiang
* Date: 2021/10/21 2:50
*/
/**
* `id` int NOT NULL AUTO_INCREMENT,
* `username` varchar(12) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL,
* `sex` varchar(2) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL,
* `age` int NULL DEFAULT NULL,
* `birthday` date NULL DEFAULT NULL,
*/
@Data
@AllArgsConstructor
@NoArgsConstructor
public class User {
private int id;
private String username;
private String sex;
private int age;
private Date birthday;
}
创建UserMapper接口
package com.xiang.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.xiang.pojo.User;
import org.springframework.stereotype.Component;
/**
* Created by IntelliJ IDEA.
* User: xiang
* Date: 2021/10/21 13:04
*/
@Component ////该注解加不加都可以,主要是为了解决自动注入时的报红问题
/**
* 使用MybatisPlus不需要再创建mapper对应的xml文件,只要继承该接口并传入相应的泛型即可
*/
public interface UserMapper extends BaseMapper<User> {
}
在启动类添加扫描注解
package com.xiang;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
@MapperScan("com.xiang.mapper")
//添加扫描注解,写入mapper的路径,否则会找不到接口并报错
public class SpringBootMybatisPlusApplication {
public static void main(String[] args) {
SpringApplication.run(SpringBootMybatisPlusApplication.class, args);
}
}
接下来进行测试
package com.xiang;
import com.xiang.mapper.UserMapper;
import com.xiang.pojo.User;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import javax.swing.*;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
@SpringBootTest
class SpringBootMybatisPlusApplicationTests {
@Autowired
UserMapper userMapper;
/**
* 查所有
*/
@Test
void findAll() {
List<User> list = userMapper.selectList(null);
for (User user : list) {
System.out.println(user);
}
}
/**
* 插入
*/
@Test
void insert() {
User user = new User();
user.setUsername("小五");
user.setSex("女");
int insert = userMapper.insert(user);
if (insert > 0) {
System.out.println("insert OK");
} else {
System.out.println("fail");
}
}
/**
* 更新
*/
@Test
void updateById() {
try {
SimpleDateFormat format = new SimpleDateFormat("YYYY-MM-dd");
Date date = format.parse("2000-1-1");
userMapper.updateById(new User(608, "小小", "女", 20, date));
User selectById = userMapper.selectById(606);
System.out.println(selectById);
} catch (ParseException e) {
e.printStackTrace();
}
}
/**
* 删除
*/
@Test
void deleteById(){
int byId = userMapper.deleteById(606);
if (byId>0){
System.out.println("deleteById OK ");
}else {
System.out.println("fail");
}
List<User> list = userMapper.selectList(null);
for (User user : list) {
System.out.println(user);
}
}
}
控制台运行结果
查所有
JDBC Connection [HikariProxyConnection@892262157 wrapping com.mysql.cj.jdbc.ConnectionImpl@70730db] will not be managed by Spring
==> Preparing: SELECT id,username,sex,age,birthday FROM user
==> Parameters:
<== Columns: id, username, sex, age, birthday
<== Row: 1, xiang, 男, 18, 2021-10-03
<== Row: 559, 小向, 男, 18, 2021-10-04
<== Row: 602, admin, 女, 18, 2021-10-20
<== Row: 603, testbox, 女, 18, 2021-10-02
<== Row: 604, 小一, 男, 18, 2021-10-16
<== Row: 605, 小二, 女, 18, null
<== Row: 607, 小四, 女, 21, null
<== Row: 608, 小五, 女, 0, null
<== Total: 8
Closing non transactional SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@b9a77c8]
插入
JDBC Connection [HikariProxyConnection@780570776 wrapping com.mysql.cj.jdbc.ConnectionImpl@37c36608] will not be managed by Spring
==> Preparing: INSERT INTO user ( id, username, sex, age ) VALUES ( ?, ?, ?, ? )
==> Parameters: 0(Integer), 小五(String), 女(String), 0(Integer)
<== Updates: 1
Closing non transactional SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@7a81065e]
insert OK
更新
JDBC Connection [HikariProxyConnection@117911771 wrapping com.mysql.cj.jdbc.ConnectionImpl@5793b87] will not be managed by Spring
==> Preparing: UPDATE user SET username=?, sex=?, age=?, birthday=? WHERE id=?
==> Parameters: 小小(String), 女(String), 20(Integer), 1999-12-26 00:00:00.0(Timestamp), 608(Integer)
<== Updates: 1
Closing non transactional SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@1645f294]
删除
JDBC Connection [HikariProxyConnection@446093644 wrapping com.mysql.cj.jdbc.ConnectionImpl@2a869a16] will not be managed by Spring
==> Preparing: DELETE FROM user WHERE id=?
==> Parameters: 608(Integer)
<== Updates: 1
Closing non transactional SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@75181b50]
deleteById OK