带你入门 MybatisPlus
Posted 南淮北安
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了带你入门 MybatisPlus相关的知识,希望对你有一定的参考价值。
文章目录
一、环境搭建
1. 准备数据库环境
创建表:
CREATE DATABASE `mybatis_plus` /*!40100 DEFAULT CHARACTER SET utf8mb4 */;
use `mybatis_plus`;
CREATE TABLE `user` (
`id` bigint(20) NOT NULL COMMENT '主键ID',
`name` varchar(30) DEFAULT NULL COMMENT '姓名',
`age` int(11) DEFAULT NULL COMMENT '年龄',
`email` varchar(50) DEFAULT NULL COMMENT '邮箱',
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
添加数据:
INSERT INTO user (id, name, age, email) VALUES
(1, 'Jone', 18, 'test1@baomidou.com'),
(2, 'Jack', 20, 'test2@baomidou.com'),
(3, 'Tom', 28, 'test3@baomidou.com'),
(4, 'Sandy', 21, 'test4@baomidou.com'),
(5, 'Billie', 24, 'test5@baomidou.com');
2. 创建 SpringBoot 工程
(1)使用 Spring Initializr 快速初始化一个 Spring Boot 工程
(2)引入依赖
<properties>
<java.version>1.8</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>
<!--mybatis-plus启动器-->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.5.1</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>8.0.21</version>
</dependency>
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-generator</artifactId>
<version>3.5.1</version>
</dependency>
</dependencies>
二、编写代码
1. 配置application.yml
spring:
# 配置数据源信息
datasource:
# 配置数据源类型
type: com.zaxxer.hikari.HikariDataSource
# 配置连接数据库的各个信息
driver-class-name: com.mysql.cj.jdbc.Driver
# 由于mysql版本为8,所以需要指定时区 serverTimezone=UTC
url: jdbc:mysql://localhost:3306/mybatis_plus?serverTimezone=UTC
username: root
password: root
# 为了查看自动生成SQL语句,加入Mybatis自带的日志功能
mybatis-plus:
configuration:
log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
2. 启动类
@SpringBootApplication
// 扫描 mapper 包
@MapperScan(basePackages = "com.yolo.mybatisplus.mapper")
public class MybatisPlusApplication
public static void main(String[] args)
SpringApplication.run(MybatisPlusApplication.class, args);
3. 添加实体
@Data //lombok注解
public class User
private Long id;
private String name;
private Integer age;
private String email;
3. 添加Mapper
BaseMapper是MyBatis-Plus提供的模板mapper,其中包含了基本的CRUD方法,泛型为操作的实体类型
public interface UserMapper extends BaseMapper<User>
三、测试
package com.yolo.mybatisplus;
import com.yolo.mybatisplus.mapper.UserMapper;
import com.yolo.mybatisplus.pojo.User;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* Date:2022/2/12
* Author:ybc
* Description:
*/
@SpringBootTest
public class MyBatisPlusTest
@Autowired
private UserMapper userMapper;
@Test
public void testSelectList()
//通过条件构造器查询一个list集合,若没有条件,则可以设置null为参数
List<User> list = userMapper.selectList(null);
list.forEach(System.out::println);
@Test
public void testInsert()
//实现新增用户信息
//INSERT INTO user ( id, name, age, email ) VALUES ( ?, ?, ?, ? )
User user = new User();
//user.setId(100L);
user.setName("张三");
user.setAge(23);
user.setEmail("zhangsan@atguigu.com");
int result = userMapper.insert(user);
System.out.println("result:"+result);
System.out.println("id:"+user.getId());
@Test
public void testDelete()
//通过id删除用户信息
//DELETE FROM user WHERE id=?
/*int result = userMapper.deleteById(1492767055210991617L);
System.out.println("result:"+result);*/
//根据map集合中所设置的条件删除用户信息
//DELETE FROM user WHERE name = ? AND age = ?
/*Map<String, Object> map = new HashMap<>();
map.put("name", "张三");
map.put("age", 23);
int result = userMapper.deleteByMap(map);
System.out.println("result:"+result);*/
//通过多个id实现批量删除
//DELETE FROM user WHERE id IN ( ? , ? , ? )
List<Long> list = Arrays.asList(1L, 2L, 3L);
int result = userMapper.deleteBatchIds(list);
System.out.println("result:"+result);
@Test
public void testUpdate()
//修改用户信息
//UPDATE user SET name=?, email=? WHERE id=?
User user = new User().setId(4L).setName("李四").setEmail("lisi@atguigu.com");
int result = userMapper.updateById(user);
System.out.println("result:"+result);
@Test
public void testSelect()
//通过id查询用户信息
//SELECT id,name,age,email FROM user WHERE id=?
/*User user = userMapper.selectById(1L);
System.out.println(user);*/
//根据多个id查询多个用户信息
//SELECT id,name,age,email FROM user WHERE id IN ( ? , ? , ? )
/*List<Long> list = Arrays.asList(1L, 2L, 3L);
List<User> users = userMapper.selectBatchIds(list);
users.forEach(System.out::println);*/
//根据map集合中的条件查询用户信息
//SELECT id,name,age,email FROM user WHERE name = ? AND age = ?
/*Map<String, Object> map = new HashMap<>();
map.put("name", "Jack");
map.put("age", 20);
List<User> users = userMapper.selectByMap(map);
users.forEach(System.out::println);*/
//查询所有数据
//SELECT id,name,age,email FROM user
List<User> users = userMapper.selectList(null);
users.forEach(System.out::println);
/*Map<String, Object> map = userMapper.selectMapById(1L);
System.out.println(map);*/
四、自定义文件
MyBatis-Plus 是一个 MyBatis的增强工具,在 MyBatis 的基础上只做增强不做改变,为简化开发、提高效率而生。
所以也可以自定义文件进行操作
引入配置文件:
<?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.yolo.mybatisplus.mapper.UserMapper">
<!--Map<String, Object> selectMapById(Long id);-->
<select id="selectMapById" resultType="map">
select id,name,age,email from user where id = #id
</select>
</mapper>
需要注意如果返回类型支持简写为实体类,需要在yml配置文件中引入别名支持:
自定义查询
@Repository
public interface UserMapper extends BaseMapper<User>
/**
* 根据id查询用户信息为map集合
* @param id
* @return
*/
Map<String, Object> selectMapById(Long id);
以上是关于带你入门 MybatisPlus的主要内容,如果未能解决你的问题,请参考以下文章