因为mybatis plus非常的流行,虽然平常mybatis generator也够用了,但多会一个,看别人的代码就轻松一点
注意事项:
1 打开Navicat运行以下SQL脚本进行建库建表
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;
2 插入几条测试数据
INSERT INTO user (id, name, age, email) VALUES
(1, 'Jone', 18, '[email protected]'),
(2, 'Jack', 20, '[email protected]'),
(3, 'Tom', 28, '[email protected]'),
(4, 'Sandy', 21, '[email protected]'),
(5, 'Billie', 24, '[email protected]');
1 引入pom依赖
<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.0modelVersion>
<parent>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-parentartifactId>
<version>2.6.8version>
<relativePath/>
parent>
<groupId>com.yggroupId>
<artifactId>mybatis-plusartifactId>
<version>0.0.1-SNAPSHOTversion>
<name>mybatis-plusname>
<description>Demo project for Spring Bootdescription>
<properties>
<java.version>1.8java.version>
properties>
<dependencies>
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-webartifactId>
dependency>
<dependency>
<groupId>org.projectlombokgroupId>
<artifactId>lombokartifactId>
<optional>trueoptional>
dependency>
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-testartifactId>
dependency>
<dependency>
<groupId>com.baomidougroupId>
<artifactId>mybatis-plus-boot-starterartifactId>
<version>3.5.1version>
dependency>
<dependency>
<groupId>mysqlgroupId>
<artifactId>mysql-connector-javaartifactId>
<scope>runtimescope>
dependency>
dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-maven-pluginartifactId>
<configuration>
<excludes>
<exclude>
<groupId>org.projectlombokgroupId>
<artifactId>lombokartifactId>
exclude>
excludes>
configuration>
plugin>
plugins>
build>
project>
3 右键user选择Scripted Extensions→Generate POJOs.groovy生成数据库user实体类
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-dsDSmpoq-1654335325208)(https://upload-images.jianshu.io/upload_images/24315796-2f9d23ea327a420f.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)]
package com.yg.mybatisplus.entity;
import lombok.Data;
@Data
public class User {
private Long id;
private String name;
private Integer age;
private String email;
}
5 创建mapper接口,集成com.baomidou.mybatisplus.core.mapper.BaseMapper可以使用增删改查方法
package com.yg.mybatisplus.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.yg.mybatisplus.entity.User;
import org.springframework.stereotype.Repository;
/**
* @Author suolong
* @Date 2022/6/2 17:25
* @Version 2.0
*/
@Repository
public interface UserMapper extends BaseMapper<User> {
}
6 application.yml配置
spring:
datasource:
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://xxx/database?severTimezone=Asia/Shanghai&allowMultiQueries=true&autoReconnect=true&characterEncoding=UTF-8&useUnicode=true&useSSL=false
username: xxx
password: 123456
#生成sql日志打印,一般关闭
mybatis-plus:
configuration:
log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
7 启动类
package com.yg.mybatisplus;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@MapperScan("com.yg.mybatisplus.mapper") //扫描所有的mapper
@SpringBootApplication
public class MybatisPlusApplication {
public static void main(String[] args) {
SpringApplication.run(MybatisPlusApplication.class, args);
}
}
8 测试CRUD增删改查
package com.yg.mybatisplus;
import com.yg.mybatisplus.entity.User;
import com.yg.mybatisplus.mapper.UserMapper;
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;
/**
* @Author suolong
* @Date 2022/6/2 17:42
* @Version 2.0
*/
@SpringBootTest
public class MybatisPlusTest {
@Autowired
UserMapper userMapper;
@Test
void selectTest(){
//全查
List<User> users = userMapper.selectList(null);
users.forEach(System.out::println);
}
/**
* 测试插入一条数据
* MyBatis-Plus在实现插入数据时,会默认基于雪花算法的策略生成id
*/
@Test
public void testInsert(){
User user = new User();
user.setName("Vz1");
user.setAge(211);
user.setEmail("[email protected]");
int result = userMapper.insert(user);
System.out.println(result > 0 ? "添加成功!" : "添加失败!");
System.out.println("受影响的行数为:" + result);
//1527206783590903810(当前 id 为雪花算法自动生成的id)
System.out.println("id自动获取" + user.getId());
}
/**
* 测试根据id删除一条数据
*/
@Test
public void testDeleteById(){
int result = userMapper.deleteById(1533011356262625282L);
System.out.println(result > 0 ? "删除成功!" : "删除失败!");
System.out.println("受影响的行数为:" + result);
}
/**
* 测试通过id批量删除数据
*/
@Test
public void testDeleteBatchIds(){
List<Long> ids = Arrays.asList(1532349895093833729L,1533012537454157826L,1533012657583161345L);
int result = userMapper.deleteBatchIds(ids);
System.out.println(result > 0 ? "删除成功!" : "删除失败!");
System.out.println("受影响的行数为:" + result);
}
/**
* 测试根据Map集合中所设置的条件删除数据
*/
@Test
public void testDeleteByMap(){
//当前演示为根据name和age删除数据
//执行SQL为:DELETE FROM user WHERE name = ? AND age = ?
Map<String,Object> map = new HashMap<>();
map.put("name","Vz1 ");
map.put("age",211);
int result = userMapper.deleteByMap(map);
System.out.println(result > 0 ? "删除成功!" : "删除失败!");
System.out.println("受影响的行数为:" + result);
}
/**
* 测试根据id修改用户信息, 只修改改变的值, 其他信息保持原值
*/
@Test
public void testUpdateById(){
//执行SQL为: UPDATE user SET name=?, age=?, email=? WHERE id=?
User user = new User();
user.setId(5L);
user.setEmail("[email protected]");
int result = userMapper.updateById(user);
System.out.println(result > 0 ? "修改成功!" : "修改失败!");
System.out.println("受影响的行数为:" + result);
}
/**
* 测试根据id查询用户数据
*/
@Test
public void testSelectById(){
User user = userMapper.selectById(1L);
System.out.println(user);
}
/**
* 根据多个id查询用户数据
*/
@Test
public void testSelectBatchIds(){
//执行SQL为:SELECT id,name,age,email FROM user WHERE id IN ( ? , ? , ? )
List<Long> ids = Arrays.asList(1L,2L,3L);
List<User> users = userMapper.selectBatchIds(ids);
users.forEach(System.out::println);
}
/**
* 根据Map所设置的条件查询用户
*/
@Test
public void testSelectByMap(){
//执行SQL为:SELECT id,name,age,email FROM user WHERE age = ?
Map<String,Object> map = new HashMap<>();
map.put("age",18);
List<User> users = userMapper.selectByMap(map);
users.forEach(System.out::println);
}
}
快使用就是查看CRUD增删改查怎么用的
作为程序员第 149 篇文章,每次写一句歌词记录一下,看看人生有几首歌的时间,wahahaha …