首先是项目结构
pom文件:
<?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.1.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.gbx</groupId>
<artifactId>mp-demo01</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>mp-demo01</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>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
</exclusion>
</exclusions>
</dependency>
<!--mybatis-plus-->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.0.5</version>
</dependency>
<!--mysql-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.13</version>
</dependency>
<!--lombok用来简化实体类-->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
application.properties文件:
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/mybatis_plus?serverTimezone=GMT%2B8
spring.datasource.username=root
spring.datasource.password=black123
server.port=8080
spring.profiles.active=dev
#mybatis日志
mybatis-plus.configuration.log-impl=org.apache.ibatis.logging.stdout.StdOutImpl
#全局设置主键生成策略
mybatis-plus.global-config.db-config.id-type=auto
#设置逻辑删除对应值(此处 1 为删除,可以使用默认)
mybatis-plus.global-config.db-config.logic-delete-value=1
mybatis-plus.global-config.db-config.logic-not-delete-value=0
实体类 entity:
BaseEntity:
package com.gbx.mpdemo01.entity;
import com.baomidou.mybatisplus.annotation.FieldFill;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableLogic;
import com.baomidou.mybatisplus.annotation.Version;
import lombok.Data;
import java.util.Date;
@Data
public class BaseEntity {
@TableField(fill = FieldFill.INSERT)
private Date createTime;
@TableField(fill = FieldFill.INSERT_UPDATE)
private Date updateTime;
@Version //乐观锁
@TableField(fill = FieldFill.INSERT)
private Integer version;
@TableLogic //逻辑删除字段设定
@TableField(fill = FieldFill.INSERT)
private Integer deleted;
}
UserEntity:
package com.gbx.mpdemo01.entity;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import lombok.Data;
@Data
public class User extends BaseEntity{
@TableId(type = IdType.ID_WORKER)
//@TableId(type = IdType.ID_WORKER_STR) 字符串类型自增长
private Long id;
private String name;
private Integer age;
private String email;
}
mapper接口集成BaseMapper<T> 就可以了,泛型选择自己的entity类型:
package com.gbx.mpdemo01.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.gbx.mpdemo01.entity.User;
public interface UserMapper extends BaseMapper<User> {
}
配置handler:
package com.gbx.mpdemo01.handler;
import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;
import java.util.Date;
@Component
public class MyMetaObjectHandler implements MetaObjectHandler {
@Override
public void insertFill(MetaObject metaObject) {
this.setFieldValByName("createTime",new Date(),metaObject);
this.setFieldValByName("updateTime",new Date(),metaObject);
this.setFieldValByName("version",1,metaObject);//乐观锁初始化
this.setFieldValByName("deleted",0,metaObject);//逻辑删除初始化
}
@Override
public void updateFill(MetaObject metaObject) {
this.setFieldValByName("updateTime",new Date(),metaObject);
}
}
添加配置类:
package com.gbx.mpdemo01.config;
import com.baomidou.mybatisplus.core.injector.ISqlInjector;
import com.baomidou.mybatisplus.extension.injector.LogicSqlInjector;
import com.baomidou.mybatisplus.extension.plugins.OptimisticLockerInterceptor;
import com.baomidou.mybatisplus.extension.plugins.PaginationInterceptor;
import com.baomidou.mybatisplus.extension.plugins.PerformanceInterceptor;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;
@Configuration
@MapperScan("com.gbx.mpdemo01.mapper") //也可以放置在启动类上
public class MpConfig {
/**
* 乐观锁插件配置
*/
@Bean
public OptimisticLockerInterceptor optimisticLockerInterceptor() {
return new OptimisticLockerInterceptor();
}
/**
* 分页插件
*/
@Bean
public PaginationInterceptor paginationInterceptor() {
return new PaginationInterceptor();
}
/**
* 逻辑删除插件
*/
@Bean
public ISqlInjector sqlInjector() {
return new LogicSqlInjector();
}
/**
* SQL 执行性能分析插件
* 开发环境使用,线上不推荐。 maxTime 指的是 sql 最大执行时长
*/
@Bean
@Profile({"dev","test"})// 设置 dev test 环境开启
public PerformanceInterceptor performanceInterceptor() {
PerformanceInterceptor performanceInterceptor = new PerformanceInterceptor();
performanceInterceptor.setMaxTime(200);//ms,超过此处设置的ms则sql不执行
performanceInterceptor.setFormat(true);
return performanceInterceptor;
}
}
启动类:
package com.gbx.mpdemo01;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class MpDemo01Application {
public static void main(String[] args) {
SpringApplication.run(MpDemo01Application.class, args);
}
}
测试类:
package com.gbx.mpdemo01;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.gbx.mpdemo01.entity.User;
import com.gbx.mpdemo01.mapper.UserMapper;
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 java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@RunWith(SpringRunner.class)
@SpringBootTest
public class MpDemo01ApplicationTests {
@Autowired
private UserMapper userMapper;
@Test
public void findAll() {
List<User> userList = userMapper.selectList(null);
System.out.println(userList);
}
@Test
public void addUser(){
User user = new User();
user.setName("yule");
user.setAge(30);
user.setEmail("yule@qq.com");
int insert = userMapper.insert(user);
System.out.println("insert:"+ insert);
}
@Test
public void updateUser(){
User user = new User();
user.setId(1258250492107075585L);
user.setAge(120);
int row = userMapper.updateById(user);
System.out.println("row:"+ row + ",user:"+ user);
}
@Test
public void testOptimisticLock(){
User user = userMapper.selectById(1258272800230092802L);
user.setAge(666);
int row = userMapper.updateById(user);
System.out.println("row:"+ row + ",user:"+ user);
}
@Test
public void findById(){
User user = userMapper.selectById(1l);
System.out.println(user);
}
@Test
public void findByIdList(){
List<User> userList = userMapper.selectBatchIds(Arrays.asList(1l, 2L, 3L));
userList.forEach(System.out::println);
}
@Test
public void findByMap(){
Map<String,Object> map = new HashMap<>();
map.put("name","石光荣");
map.put("age",46);
List<User> userList = userMapper.selectByMap(map);
userList.forEach(System.out::println);
}
@Test
public void findByPage(){
Page<User> userPage = new Page<>(1,3);
userMapper.selectPage(userPage,null);
userPage.getRecords().forEach(System.out::println);
System.out.println("currentPage:" + userPage.getCurrent());
System.out.println("size:" + userPage.getSize());
System.out.println("total:" + userPage.getTotal());
System.out.println("pages:" + userPage.getPages());
System.out.println(userPage.hasNext());
System.out.println(userPage.hasPrevious());
}
@Test
public void deleteById(){
int result = userMapper.deleteById(1258285643637731329l);
System.out.println(result);
}
@Test
public void findByWrapper(){
QueryWrapper<User> queryWrapper = new QueryWrapper<>();
//ge,gt,le,lt
queryWrapper.ge("age",20);
//select
queryWrapper.select("id","name");
List<User> userList = userMapper.selectList(queryWrapper);
userList.forEach(System.out::println);
}
}
扩展(可以下载为知笔记版wrapper,已共享,详见资源链接):