目录
1. Mybatis-Plus概念
1.1 Mybatis-Plus介绍
1.3 架构
1.4 作者
2. Mybatis-Plus快速⼊⻔
2.1 安装
2.2 创建数据库以及表
2.3 创建⼯程
2.4 Mybatis + MP
2.5 Spring + Mybatis + MP
2.6 SpringBoot + Mybatis + MP
3. 通⽤CRUD
3.1 插⼊操作
3.2 更新操作
3.3 删除操作
3.3.4、deleteBatchIds
3.4 查询操作
3.4.1、selectById
3.4.2、selectBatchIds
3.4.3、selectOne
3.4.4、selectCount
3.4.5、selectList
3.4.6、selectPage
3.5 SQL注⼊的原理
4. 配置
4.1、基本配置
4.1.1、configLocation
4.1.2、mapperLocations
4.1.3、typeAliasesPackage
4.2、进阶配置
4.2.1、mapUnderscoreToCamelCase
4.2.2、cacheEnabled
4.3、DB 策略配置
4.3.1、idType
4.3.2、tablePrefix
5. 条件构造器
5.1、allEq
5.1.1、说明
5.1.2、测试⽤例
5.2、基本⽐较操作
5.3、模糊查询
5.4、排序
5.6、select
6. ActiveRecord
6.1、开启AR之旅
6.3、新增数据
编辑
6.4、更新操作
编辑
6.5、删除操作
6.6、根据条件查询
7. 插件
7.1、mybatis的插件机制
7.2、执⾏分析插件
7.3、性能分析插件
7.4、乐观锁插件
7.4.1、主要适⽤场景
7.4.2、插件配置
7.4.3、注解实体字段
7.4.4、测试
7.4.5、特别说明
8. Sql 注⼊器
8.1、编写MyBaseMapper
8.2、编写MySqlInjector
8.3、编写FindAll
8.4、注册到Spring容器
8.5、测试
9. ⾃动填充功能
9.1、添加@TableField注解
9.2、编写MyMetaObjectHandler
9.3、测试
10. 逻辑删除
10.1、修改表结构
10.2、配置
10.3、测试
11. 代码⽣成器
11.1、创建⼯程
11.2、代码
11.3、测试
12. MybatisX 快速开发插件
com.baomidou
mybatis-plus-boot-starter
3.4.0
com.baomidou
mybatis-plus
3.4.0
-- 创建测试表
DROP TABLE IF EXISTS tb_user;
CREATE TABLE user
(
id BIGINT(20) NOT NULL COMMENT '主键ID',
name VARCHAR(30) NULL DEFAULT NULL COMMENT '姓名',
age INT(11) NULL DEFAULT NULL COMMENT '年龄',
email VARCHAR(50) NULL DEFAULT NULL COMMENT '邮箱',
PRIMARY KEY (id)
);
-- 插⼊测试数据
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]');
导⼊依赖:
com.baomidou
mybatis-plus
3.1.1
mysql
mysql-connector-java
5.1.47
com.alibaba
druid
1.0.11
org.projectlombok
lombok
1.18.4
junit
junit
4.12
org.slf4j
slf4j-log4j12
1.6.4
org.apache.maven.plugins
maven-compiler-plugin
1.8
lagou-mybatis-plus
com.lagou.mp
1.0-SNAPSHOT
4.0.0
lagou-mybatis-plus-simple
log4j.rootLogger=DEBUG,A1
log4j.appender.A1=org.apache.log4j.ConsoleAppender
log4j.appender.A1.layout=org.apache.log4j.PatternLayout
log4j.appender.A1.layout.ConversionPattern=[%t] [%c]-[%p] %m%n
@Data // getter setter @toString
@NoArgsConstructor
@AllArgsConstructor
public class User {
private Long id;
private String name;
private Integer age;
private String email; }
public interface UserMapper {
List findAll();
}
public class MPTest {
@Test
public void test1() throws IOException {
InputStream resourceAsStream =
Resources.getResourceAsStream("sqlMapConfig.xml");
SqlSessionFactory sqlSessionFactory = new
SqlSessionFactoryBuilder().build(resourceAsStream);
SqlSession sqlSession = sqlSessionFactory.openSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
List all = mapper.findAll();
for (User user : all) {
System.out.println(user);
}
}
}
User(id=1, name=Jone, age=18, [email protected])
User(id=2, name=Jack, age=20, [email protected])
User(id=3, name=Tom, age=28, [email protected])
User(id=4, name=Sandy, age=21, [email protected])
User(id=5, name=Billie, age=24, [email protected])
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.lagou.pojo.User;
public interface UserMapper extends BaseMapper {
}
@Test
public void test2() throws IOException {
InputStream resourceAsStream =
Resources.getResourceAsStream("sqlMapConfig.xml");
//这⾥使⽤的是MP中的MybatisSqlSessionFactoryBuilder
SqlSessionFactory sqlSessionFactory = new
MybatisSqlSessionFactoryBuilder().build(resourceAsStream);
SqlSession sqlSession = sqlSessionFactory.openSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
// 可以调⽤BaseMapper中定义的⽅法
List all = mapper.selectList(null);
for (User user : all) {
System.out.println(user);
}
}
User(id=1, name=Jone, age=18, [email protected])
User(id=2, name=Jack, age=20, [email protected])
User(id=3, name=Tom, age=28, [email protected])
User(id=4, name=Sandy, age=21, [email protected])
User(id=5, name=Billie, age=24, [email protected])
lagou-mybatis-plus
com.lagou.mp
1.0-SNAPSHOT
4.0.0
lagou-mybatis-plus-spring
5.1.6.RELEASE
org.springframework
spring-webmvc
${spring.version}
org.springframework
spring-jdbc
${spring.version}
org.springframework
spring-test
${spring.version}
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://127.0.0.1:3306/mp?serverTimezone=GMT%2B8&useSSL=false
jdbc.username=root
jdbc.password=root
@Data
@NoArgsConstructor
@AllArgsConstructor
public class User {
private Long id;
private String name;
private Integer age;
private String email; }
public interface UserMapper extends BaseMapper {
List findAll();
}
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:applicationContext.xml")
public class TestSpringMP {
@Autowired
private UserMapper userMapper;
@Test
public void test2() throws IOException {
List users = this.userMapper.selectList(null);
for (User user : users) {
System.out.println(user);
}
}
org.springframework.boot
spring-boot-starter
org.springframework.boot
spring-boot-starter-logging
org.springframework.boot
spring-boot-starter-test
test
org.projectlombok
lombok
true
com.baomidou
mybatis-plus-boot-starter
3.1.1
mysql
mysql-connector-java
5.1.47
org.slf4j
slf4j-log4j12
org.springframework.boot
spring-boot-maven-plugin
log4j.rootLogger=DEBUG,A1
log4j.appender.A1=org.apache.log4j.ConsoleAppender
log4j.appender.A1.layout=org.apache.log4j.PatternLayout
log4j.appender.A1.layout.ConversionPattern=[%t] [%c]-[%p] %m%n
编写application.properties
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.url=jdbc:mysql://127.0.0.1:3306/mp?
useUnicode=true&characterEncoding=utf8&autoReconnect=true&allowMultiQueries=tr
ue&useSSL=false
spring.datasource.username=root
spring.datasource.password=root
编写pojo
@Data
@NoArgsConstructor
@AllArgsConstructor
public class User {
private Long id;
private String name;
private Integer age;
private String email;
}
public interface UserMapper extends BaseMapper {
}
package com.lagou.mp;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.WebApplicationType;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
@MapperScan("com.lagou.mp.mapper") //设置mapper接⼝的扫描包
@SpringBootApplication
public class MyApplication {
public static void main(String[] args) {
SpringApplication.run(MyApplication.class, args);
}
}
编写测试⽤例
package com.lagou.mp;
import com.lagou.mp.mapper.UserMapper;
import com.lagou.mp.pojo.User;
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.List;
@RunWith(SpringRunner.class)
@SpringBootTest
public class UserMapperTest {
@Autowired
private UserMapper userMapper;
@Test
public void testSelect() {
List userList = userMapper.selectList(null);
for (User user : userList) {
System.out.println(user);
}
}
}
User(id=1, name=Jone, age=18, [email protected])
User(id=2, name=Jack, age=20, [email protected])
User(id=3, name=Tom, age=28, [email protected])
User(id=4, name=Sandy, age=21, [email protected])
User(id=5, name=Billie, age=24, [email protected])
/**
* 插⼊⼀条记录
*
* @param entity 实体对象.
*/
int insert(T entity);
@RunWith(SpringRunner.class)
@SpringBootTest
public class UserMapperTest {
@Autowired
private UserMapper userMapper;
@Test
public void testInsert(){
User user = new User();
user.setAge(18);
user.setEmail("[email protected]");
user.setName("⼦慕");
//返回的result是受影响的⾏数,并不是⾃增后的id
int result = userMapper.insert(user);
System.out.println(result);
System.out.println(user.getId());
}
}
11318744682116739074
package com.baomidou.mybatisplus.annotation;
import lombok.Getter;
/**
* ⽣成ID类型枚举类
*
* @author hubin
* @since 2015-11-10
*/
@Getter
public enum IdType {
/**
* 数据库ID⾃增
*/
AUTO(0),
/**
* 该类型为未设置主键类型
*/
NONE(1),
/**
* ⽤户输⼊ID
* 该类型可以通过⾃⼰注册⾃动填充插件进⾏填充
*/
INPUT(2),
/* 以下3种类型、只有当插⼊对象ID 为空,才⾃动填充。 */
/**
* 全局唯⼀ID (idWorker)
*/
ID_WORKER(3),
/**
* 全局唯⼀ID (UUID)
*/
UUID(4),
/**
* 字符串全局唯⼀ID (idWorker 的字符串表示)
*/
ID_WORKER_STR(5);
private final int key;
IdType(int key) {
this.key = key;
}
}
package com.lagou.mp.pojo;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@NoArgsConstructor
@AllArgsConstructor
@TableName("tb_user")
public class User {
@TableId(type = IdType.AUTO) //指定id类型为⾃增⻓
private Long id;
private String userName;
private String password;
private String name;
private Integer age;
private String email;
}
其他⽤法,如⼤字段不加⼊查询字段:
效果:
/**
* 根据 ID 修改
*
* @param entity 实体对象
*/
int updateById(@Param(Constants.ENTITY) T entity);
@RunWith(SpringRunner.class)
@SpringBootTest
public class UserMapperTest {
@Autowired
private UserMapper userMapper;
@Test
public void testUpdateById() {
User user = new User();
user.setId(6L); //主键
user.setAge(21); //更新的字段
//根据id更新,更新不为null的字段
this.userMapper.updateById(user);
}
}
/**
* 根据 whereEntity 条件,更新记录
*
* @param entity 实体对象 (set 条件值,可以为 null)
* @param updateWrapper 实体对象封装操作类(可以为 null,⾥⾯的 entity ⽤于⽣成
where 语句)
*/
int update(@Param(Constants.ENTITY) T entity, @Param(Constants.WRAPPER)
Wrapper updateWrapper);
package com.lagou.mp;
import com.lagou.mp.mapper.UserMapper;
import com.lagou.mp.pojo.User;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import net.minidev.json.writer.UpdaterMapper;
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.List;
@RunWith(SpringRunner.class)
@SpringBootTest
public class UserMapperTest {
@Autowired
private UserMapper userMapper;
@Test
public void testUpdate() {
User user = new User();
user.setAge(22); //更新的字段
//更新的条件
QueryWrapper wrapper = new QueryWrapper<>();
wrapper.eq("id", 6);
//执⾏更新操作
int result = this.userMapper.update(user, wrapper);
System.out.println("result = " + result);
}
}
@Test
public void testUpdate() {
//更新的条件以及字段
UpdateWrapper wrapper = new UpdateWrapper<>();
wrapper.eq("id", 6).set("age", 23);
//执⾏更新操作
int result = this.userMapper.update(null, wrapper);
System.out.println("result = " + result);
}
[main] [com.lagou.mp.mapper.UserMapper.update]-[DEBUG] == > Preparing: UPDATEtb_user SET age = ? WHERE id = ?[main] [com.lagou.mp.mapper.UserMapper.update]-[DEBUG] == > Parameters:23 (Integer), 6 (Integer)[main] [com.lagou.mp.mapper.UserMapper.update]-[DEBUG] < == Updates: 1
/**
* 根据 ID 删除
*
* @param id 主键ID
*/
int deleteById(Serializable id);
package com.lagou.mp;
import com.lagou.mp.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;
@RunWith(SpringRunner.class)
@SpringBootTest
public class UserMapperTest {
@Autowired
private UserMapper userMapper;
@Test
public void testDeleteById() {
//执⾏删除操作
int result = this.userMapper.deleteById(6L);
System.out.println("result = " + result);
}
}
结果:
[main] [com.lagou.mp.mapper.UserMapper.deleteById]-[DEBUG] == > Preparing:DELETE FROM tb_user WHERE id = ?[main] [com.lagou.mp.mapper.UserMapper.deleteById]-[DEBUG] == > Parameters:6 (Long)[main] [com.lagou.mp.mapper.UserMapper.deleteById]-[DEBUG] < == Updates: 1
/**
* 根据 columnMap 条件,删除记录
*
* @param columnMap 表字段 map 对象
*/
int deleteByMap(@Param(Constants.COLUMN_MAP) Map
columnMap);
package com.lagou.mp;
import com.lagou.mp.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.HashMap;
import java.util.Map;
@RunWith(SpringRunner.class)
@SpringBootTest
public class UserMapperTest {
@Autowired
private UserMapper userMapper;
@Test
public void testDeleteByMap() {
Map columnMap = new HashMap<>();
columnMap.put("age",21);
columnMap.put("name","⼦慕");
//将columnMap中的元素设置为删除的条件,多个之间为and关系
int result = this.userMapper.deleteByMap(columnMap);
System.out.println("result = " + result);
}
}
结果:
[main] [com.lagou.mp.mapper.UserMapper.deleteByMap]-[DEBUG] == > Preparing:DELETE FROM tb_user WHERE name = ? AND age = ?[main] [com.lagou.mp.mapper.UserMapper.deleteByMap]-[DEBUG] == > Parameters: ⼦慕 (String), 21 (Integer)[main] [com.lagou.mp.mapper.UserMapper.deleteByMap]-[DEBUG] < == Updates: 0
/**
* 根据 entity 条件,删除记录
*
* @param wrapper 实体对象封装操作类(可以为 null)
*/
int delete(@Param(Constants.WRAPPER) Wrapper wrapper);
package com.lagou.mp;
import com.lagou.mp.mapper.UserMapper;
import com.lagou.mp.pojo.User;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.junit.Test;
结果:
3.3.4、deleteBatchIds
⽅法定义:
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.HashMap;
import java.util.Map;
@RunWith(SpringRunner.class)
@SpringBootTest
public class UserMapperTest {
@Autowired
private UserMapper userMapper;
@Test
public void testDeleteByMap() {
User user = new User();
user.setAge(20);
user.setName("⼦慕");
//将实体对象进⾏包装,包装为操作条件
QueryWrapper wrapper = new QueryWrapper<>(user);
int result = this.userMapper.delete(wrapper);
System.out.println("result = " + result);
}
}
结果:
[main] [com.lagou.mp.mapper.UserMapper.delete]-[DEBUG] == > Preparing: DELETEFROM tb_user WHERE name = ? AND age = ?[main] [com.lagou.mp.mapper.UserMapper.delete]-[DEBUG] == > Parameters: ⼦慕(String), 20 (Integer)[main] [com.lagou.mp.mapper.UserMapper.delete]-[DEBUG] < == Updates: 0
/**
* 删除(根据ID 批量删除)
*
* @param idList 主键ID列表(不能为 null 以及 empty)
*/
int deleteBatchIds(@Param(Constants.COLLECTION) Collection extends
Serializable> idList);
package com.lagou.mp;
import com.lagou.mp.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;
@RunWith(SpringRunner.class)
@SpringBootTest
public class UserMapperTest {
@Autowired
private UserMapper userMapper;
@Test
public void testDeleteByMap() {
//根据id集合批量删除
int result =
this.userMapper.deleteBatchIds(Arrays.asList(1L,10L,20L));
System.out.println("result = " + result);
}
}
[main] [com.lagou.mp.mapper.UserMapper.deleteBatchIds]-[DEBUG] == > Preparing:DELETE FROM tb_user WHERE id IN ( ? , ? , ? )[main] [com.lagou.mp.mapper.UserMapper.deleteBatchIds]-[DEBUG] == > Parameters:1 (Long), 10 (Long), 20 (Long)[main] [com.lagou.mp.mapper.UserMapper.deleteBatchIds]-[DEBUG] < == Updates:1
/**
* 根据 ID 查询
*
* @param id 主键ID
*/
T selectById(Serializable id);
package com.lagou.mp;
import com.lagou.mp.mapper.UserMapper;
import com.lagou.mp.pojo.User;
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;
@RunWith(SpringRunner.class)
@SpringBootTest
public class UserMapperTest {
@Autowired
private UserMapper userMapper;
@Test
public void testSelectById() {
//根据id查询数据
User user = this.userMapper.selectById(2L);
System.out.println("result = " + user);
}
}
/**
* 查询(根据ID 批量查询)
*
* @param idList 主键ID列表(不能为 null 以及 empty)
*/
List selectBatchIds(@Param(Constants.COLLECTION) Collection extends
Serializable> idList);
package com.lagou.mp;
import com.lagou.mp.mapper.UserMapper;
import com.lagou.mp.pojo.User;
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.List;
@RunWith(SpringRunner.class)
@SpringBootTest
public class UserMapperTest {
@Autowired
private UserMapper userMapper;
@Test
public void testSelectBatchIds() {
//根据id集合批量查询
List users = this.userMapper.selectBatchIds(Arrays.asList(2L,
3L, 10L));
for (User user : users) {
System.out.println(user);
}
}
}
/**
* 根据 entity 条件,查询⼀条记录
*
* @param queryWrapper 实体对象封装操作类(可以为 null)
*/
T selectOne(@Param(Constants.WRAPPER) Wrapper queryWrapper);
package com.lagou.mp;
import com.lagou.mp.mapper.UserMapper;
import com.lagou.mp.pojo.User;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
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;
@RunWith(SpringRunner.class)
@SpringBootTest
public class UserMapperTest {
@Autowired
private UserMapper userMapper;
@Test
public void testSelectOne() {
QueryWrapper wrapper = new QueryWrapper();
wrapper.eq("name", "jack");
//根据条件查询⼀条数据,如果结果超过⼀条会报错
User user = this.userMapper.selectOne(wrapper);
System.out.println(user);
}
}
/**
* 根据 Wrapper 条件,查询总记录数
*
* @param queryWrapper 实体对象封装操作类(可以为 null)
*/
Integer selectCount(@Param(Constants.WRAPPER) Wrapper queryWrapper);
package com.lagou.mp;
import com.lagou.mp.mapper.UserMapper;
import com.lagou.mp.pojo.User;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
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;
@RunWith(SpringRunner.class)
@SpringBootTest
public class UserMapperTest {
@Autowired
private UserMapper userMapper;
@Test
public void testSelectCount() {
QueryWrapper wrapper = new QueryWrapper();
wrapper.gt("age", 23); //年龄⼤于23岁
//根据条件查询数据条数
Integer count = this.userMapper.selectCount(wrapper);
System.out.println("count = " + count);
}
}
count = 2
/**
* 根据 entity 条件,查询全部记录
*
* @param queryWrapper 实体对象封装操作类(可以为 null)
*/
List selectList(@Param(Constants.WRAPPER) Wrapper queryWrapper);
package com.lagou.mp;
import com.lagou.mp.mapper.UserMapper;
import com.lagou.mp.pojo.User;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
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.List;
@RunWith(SpringRunner.class)
@SpringBootTest
public class UserMapperTest {
@Autowired
private UserMapper userMapper;
@Test
public void testSelectList() {
QueryWrapper wrapper = new QueryWrapper();
wrapper.gt("age", 23); //年龄⼤于23岁
//根据条件查询数据
List users = this.userMapper.selectList(wrapper);
for (User user : users) {
System.out.println("user = " + user);
}
}
}
/**
* 根据 entity 条件,查询全部记录(并翻⻚)
*
* @param page 分⻚查询条件(可以为 RowBounds.DEFAULT)
* @param queryWrapper 实体对象封装操作类(可以为 null)
*/
IPage selectPage(IPage page, @Param(Constants.WRAPPER) Wrapper
queryWrapper);
package com.lagou.mp;
import com.baomidou.mybatisplus.extension.plugins.PaginationInterceptor;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
@MapperScan("com.lagou.mp.mapper") //设置mapper接⼝的扫描包
public class MybatisPlusConfig {
/**
* 分⻚插件
*/
@Bean
public PaginationInterceptor paginationInterceptor() {
return new PaginationInterceptor();
}
}
package com.lagou.mp;
import com.lagou.mp.mapper.UserMapper;
import com.lagou.mp.pojo.User;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
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.List;
@RunWith(SpringRunner.class)
@SpringBootTest
public class UserMapperTest {
@Autowired
private UserMapper userMapper;
@Test
public void testSelectPage() {
QueryWrapper wrapper = new QueryWrapper();
wrapper.gt("age", 20); //年龄⼤于20岁
Page page = new Page<>(1,1);
//根据条件查询数据
IPage iPage = this.userMapper.selectPage(page, wrapper);
System.out.println("数据总条数:" + iPage.getTotal());
System.out.println("总⻚数:" + iPage.getPages());
List users = iPage.getRecords();
for (User user : users) {
System.out.println("user = " + user);
}
}
}
结果:
数据总条数: 4总⻚数: 4
@Override
public void inspectInject(MapperBuilderAssistant builderAssistant, Class>
mapperClass) {
Class> modelClass = extractModelClass(mapperClass);
if (modelClass != null) {
String className = mapperClass.toString();
Set mapperRegistryCache =
GlobalConfigUtils.getMapperRegistryCache(builderAssistant.getConfiguration());
if (!mapperRegistryCache.contains(className)) {
List methodList = this.getMethodList();
if (CollectionUtils.isNotEmpty(methodList)) {
TableInfo tableInfo =
TableInfoHelper.initTableInfo(builderAssistant, modelClass);
// 循环注⼊⾃定义⽅法
methodList.forEach(m -> m.inject(builderAssistant,
mapperClass, modelClass, tableInfo));
} else {
logger.debug(mapperClass.toString() + ", No effective
injection method was found.");
}
mapperRegistryCache.add(className);
}
}
}
/**
* 注⼊⾃定义 MappedStatement
*
* @param mapperClass mapper 接⼝
* @param modelClass mapper 泛型
* @param tableInfo 数据库表反射信息
* @return MappedStatement
*/
public abstract MappedStatement injectMappedStatement(Class>
mapperClass, Class> modelClass, TableInfo tableInfo);
public class SelectById extends AbstractMethod {
@Override
public MappedStatement injectMappedStatement(Class> mapperClass, Class
> modelClass, TableInfo tableInfo) {
SqlMethod sqlMethod = SqlMethod.LOGIC_SELECT_BY_ID;
SqlSource sqlSource = new RawSqlSource(configuration,
String.format(sqlMethod.getSql(),
sqlSelectColumns(tableInfo, false),
tableInfo.getTableName(), tableInfo.getKeyColumn(),
tableInfo.getKeyProperty(),
tableInfo.getLogicDeleteSql(true, false)), Object.class);
return this.addSelectMappedStatement(mapperClass,
sqlMethod.getMethod(), sqlSource, modelClass, tableInfo);
}
}
mybatis-plus.config-location = classpath:mybatis-config.xml
Spring MVC:
mybatis-plus.mapper-locations = classpath*:mybatis/*.xml
package com.lagou.mp.mapper;
import com.lagou.mp.pojo.User;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
public interface UserMapper extends BaseMapper {
User findById(Long id);
}
package com.lagou.mp;
import com.lagou.mp.mapper.UserMapper;
import com.lagou.mp.pojo.User;
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;
@RunWith(SpringRunner.class)
@SpringBootTest
public class UserMapperTest {
@Autowired
private UserMapper userMapper;
@Test
public void testSelectPage() {
User user = this.userMapper.findById(2L);
System.out.println(user);
}
}
mybatis-plus.type-aliases-package = com.lagou.mp.pojo
注意:此属性在 MyBatis 中原默认值为 false ,在 MyBatis-Plus 中,此属性也将⽤于⽣成最终的 SQL 的select body如果您的数据库命名符合规则⽆需使⽤ @TableField 注解指定数据库字段名
#关闭⾃动驼峰映射,该参数不能和mybatis-plus.config-location同时存在
mybatis-plus.configuration.map-underscore-to-camel-case=false
mybatis-plus.configuration.cache-enabled=false
mybatis-plus.global-config.db-config.id-type=auto
mybatis-plus.global-config.db-config.table-prefix=tb_
说明 :QueryWrapper(LambdaQueryWrapper) 和 UpdateWrapper(LambdaUpdateWrapper) 的⽗类⽤于⽣成 sql 的 where 条件 , entity 属性也⽤于⽣成 sql 的 where 条件注意 : entity ⽣成的 where 条件与 使⽤各个 api ⽣成的 where 条件 没有任何关联⾏为
allEq(Map params)
allEq(Map params, boolean null2IsNull)
allEq(boolean condition, Map params, boolean null2IsNull)
个别参数说明 :params : key 为数据库字段名 , value 为字段值null2IsNull : 为 true 则在 map 的 value 为 null 时调⽤ isNull ⽅法 , 为 false 时则忽略 value 为 null 的例 1: allEq({id:1,name:" ⽼王 ",age:null}) ---> id = 1 and name = ' ⽼王 ' and ageis null例 2: allEq({id:1,name:" ⽼王 ",age:null}, false) ---> id = 1 and name = ' ⽼王 '
allEq(BiPredicate filter, Map params)
allEq(BiPredicate filter, Map params, boolean null2IsNull)
allEq(boolean condition, BiPredicate filter, Map params, boolean
null2IsNull)
个别参数说明 :filter : 过滤函数 , 是否允许字段传⼊⽐对条件中params 与 null2IsNull : 同上例 1: allEq((k,v) -> k.indexOf("a") > 0, {id:1,name:" ⽼王 ",age:null}) ---> name = ' ⽼王 ' and age is null例 2: allEq((k,v) -> k.indexOf("a") > 0, {id:1,name:" ⽼王 ",age:null},false) ---> name = ' ⽼王 '
package com.lagou.mp;
import com.lagou.mp.mapper.UserMapper;
import com.lagou.mp.pojo.User;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
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.HashMap;
import java.util.List;
import java.util.Map;
@RunWith(SpringRunner.class)
@SpringBootTest
public class UserMapperTest {
@Autowired
private UserMapper userMapper;
@Test
public void testWrapper() {
QueryWrapper wrapper = new QueryWrapper<>();
//设置条件
Map params = new HashMap<>();
params.put("name", "jack");
params.put("age", "20");
// wrapper.allEq(params);//SELECT * FROM tb_user WHERE password IS NULL
AND name = ? AND age = ?
// wrapper.allEq(params,false); //SELECT * FROM tb_user WHERE name = ?
AND age = ?
// wrapper.allEq((k, v) -> (k.equals("name") || k.equals("age"))
,params);//SELECT * FROM tb_user WHERE name = ? AND age = ?
List users = this.userMapper.selectList(wrapper);
for (User user : users) {
System.out.println(user);
}
}
}
package com.lagou.mp;
import com.lagou.mp.mapper.UserMapper;
import com.lagou.mp.pojo.User;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
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.List;
@RunWith(SpringRunner.class)
@SpringBootTest
public class UserMapperTest {
@Autowired
private UserMapper userMapper;
QueryWrapper wrapper = new QueryWrapper<>();
//SELECT id,name,age,email FROM tb_user WHERE password = ? AND age >=
? AND name IN (?,?,?)
wrapper.eq("email", "[email protected]")
.ge("age", 20)
.in("name", "jack", "jone", "tom");
List users = this.userMapper.selectList(wrapper);
for (User user : users) {
System.out.println(user);
}
}
}
package com.lagou.mp;
import com.lagou.mp.mapper.UserMapper;
import com.lagou.mp.pojo.User;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
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.List;
@RunWith(SpringRunner.class)
@SpringBootTest
public class UserMapperTest {
@Autowired
private UserMapper userMapper;
@Test
public void testWrapper() {
QueryWrapper wrapper = new QueryWrapper<>();
//SELECT id,user_name,password,name,age,email FROM tb_user WHERE name
LIKE ?
//Parameters: %⼦%(String)
wrapper.like("name", "⼦");
List users = this.userMapper.selectList(wrapper);
for (User user : users) {
System.out.println(user);
}
}
}
package com.lagou.mp;
import com.lagou.mp.mapper.UserMapper;
import com.lagou.mp.pojo.User;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
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.List;
@RunWith(SpringRunner.class)
@SpringBootTest
public class UserMapperTest {
@Autowired
private UserMapper userMapper;
@Test
public void testWrapper() {
QueryWrapper wrapper = new QueryWrapper<>();
//SELECT id,user_name,password,name,age,email FROM tb_user ORDER BY
age DESC
wrapper.orderByDesc("age");
List users = this.userMapper.selectList(wrapper);
for (User user : users) {
System.out.println(user);
}
}
}
5.5、逻辑查询
package com.lagou.mp;
import com.lagou.mp.mapper.UserMapper;
import com.lagou.mp.pojo.User;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
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.List;
@RunWith(SpringRunner.class)
@SpringBootTest
public class UserMapperTest {
@Autowired
private UserMapper userMapper;
@Test
public void testWrapper() {
QueryWrapper wrapper = new QueryWrapper<>();
//SELECT id,user_name,password,name,age,email FROM tb_user WHERE name= ? OR age = ?
wrapper.eq("name","jack").or().eq("age", 24);
List users = this.userMapper.selectList(wrapper);
for (User user : users) {
System.out.println(user);
}
}
}
package com.lagou.mp;
import com.lagou.mp.mapper.UserMapper;
import com.lagou.mp.pojo.User;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
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.List;
@RunWith(SpringRunner.class)
@SpringBootTest
public class UserMapperTest {
@Autowired
private UserMapper userMapper;
@Test
public void testWrapper() {
QueryWrapper wrapper = new QueryWrapper<>();
//SELECT id,name,age FROM tb_user WHERE name = ? OR age = ?
wrapper.eq("name", "jack")
.or()
.eq("age", 24)
.select("id", "name", "age");
List users = this.userMapper.selectList(wrapper);
for (User user : users) {
System.out.println(user);
}
}
}
什么是 ActiveRecord ?ActiveRecord 也属于 ORM (对象关系映射)层,由 Rails 最早提出,遵循标准的 ORM 模型:表映射到记录,记录映射到对象,字段映射到对象属性。配合遵循的命名和配置惯例,能够很⼤程度的快速实现模型的操作,⽽且简洁易懂。ActiveRecord 的主要思想是:
- 每⼀个数据库表对应创建⼀个类,类的每⼀个对象实例对应于数据库中表的⼀⾏记录;通常 表的每个字段在类中都有相应的Field;
- ActiveRecord同时负责把⾃⼰持久化,在ActiveRecord中封装了对数据库的访问,即 CURD;;
- ActiveRecord是⼀种领域模型(Domain Model),封装了部分业务逻辑;
package com.lagou.mp.pojo;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import com.baomidou.mybatisplus.extension.activerecord.Model;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@NoArgsConstructor
@AllArgsConstructor
public class User extends Model {
private Long id;
private String userName;
private String password;
private String name;
private Integer age;
private String email;
}
6.2、根据主键查询
@RunWith(SpringRunner.class)
@SpringBootTest
public class UserMapperTest {
@Autowired
private UserMapper userMapper;
@Test
public void testAR() {
User user = new User();
user.setId(2L);
User user2 = user.selectById();
System.out.println(user2);
}
}
@RunWith(SpringRunner.class)
@SpringBootTest
public class UserMapperTest {
@Autowired
private UserMapper userMapper;
@Test
public void testARInsert() {
User user = new User();
user.setName("应颠");
user.setAge(30);
user.setEmail("[email protected]");
boolean insert = user.insert();
System.out.println(insert);
}
}
[main] [com.lagou.mp.mapper.UserMapper.insert]-[DEBUG] == > Preparing: INSERTINTO tb_user ( name, age, email ) VALUES ( ?, ?, ?, ?, ? )[main] [com.lagou.mp.mapper.UserMapper.insert]-[DEBUG] == > Parameters: 应癫[main] [com.lagou.mp.mapper.UserMapper.insert]-[DEBUG] < == Updates: 1
@RunWith(SpringRunner.class)
@SpringBootTest
public class UserMapperTest {
@Autowired
private UserMapper userMapper;
@Test
public void testAR() {
User user = new User();
user.setId(8L);
user.setAge(35);
boolean update = user.updateById();
System.out.println(update);
}
}
[main] [com.lagou.mp.mapper.UserMapper.updateById]-[DEBUG] == > Preparing:UPDATE tb_user SET age = ? WHERE id = ?[main] [com.lagou.mp.mapper.UserMapper.updateById]-[DEBUG] == > Parameters:35 (Integer), 8 (Long)[main] [com.lagou.mp.mapper.UserMapper.updateById]-[DEBUG] < == Updates: 1
@RunWith(SpringRunner.class)
@SpringBootTest
public class UserMapperTest {
@Autowired
private UserMapper userMapper;
@Test
public void testAR() {
User user = new User();
user.setId(7L);
boolean delete = user.deleteById();
System.out.println(delete);
}
}
结果:
[main] [com.lagou.mp.mapper.UserMapper.deleteById]-[DEBUG] == > Preparing:DELETE FROM tb_user WHERE id = ?[main] [com.lagou.mp.mapper.UserMapper.deleteById]-[DEBUG] == > Parameters:7 (Long)[main] [com.lagou.mp.mapper.UserMapper.deleteById]-[DEBUG] < == Updates: 1
@RunWith(SpringRunner.class)
@SpringBootTest
public class UserMapperTest {
@Autowired
private UserMapper userMapper;
@Test
public void testARFindById() {
User user = new User();
QueryWrapper userQueryWrapper = new QueryWrapper<>();
userQueryWrapper.le("age","20");
List users = user.selectList(userQueryWrapper);
for (User user1 : users) {
System.out.println(user1);
}
}
}
package com.lagou.mp.plugins;
import org.apache.ibatis.executor.Executor;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.plugin.*;
import java.util.Properties;
@Intercepts({@Signature(
type= Executor.class,
method = "update",
args = {MappedStatement.class,Object.class})})
public class MyInterceptor implements Interceptor {
@Override
public Object intercept(Invocation invocation) throws Throwable {
//拦截⽅法,具体业务逻辑编写的位置
return invocation.proceed();
}
@Override
public Object plugin(Object target) {
//创建target对象的代理对象,⽬的是将当前拦截器加⼊到该对象中
return Plugin.wrap(target, this);
}
@Override
public void setProperties(Properties properties) {
//属性设置
}
}
注⼊到Spring容器:
/**
* ⾃定义拦截器
*/
@Bean
public MyInterceptor myInterceptor(){
return new MyInterceptor();
}
或者通过xml配置,mybatis-config.xml:
@Bean
public SqlExplainInterceptor sqlExplainInterceptor(){
SqlExplainInterceptor sqlExplainInterceptor = new SqlExplainInterceptor();
List sqlParserList = new ArrayList<>();
// 攻击 SQL 阻断解析器、加⼊解析链
sqlParserList.add(new BlockAttackSqlParser());
sqlExplainInterceptor.setSqlParserList(sqlParserList);
return sqlExplainInterceptor; }
@Test
public void testUpdate(){
User user = new User();
user.setAge(20);
int result = this.userMapper.update(user, null);
System.out.println("result = " + result);
}
Caused by: com.baomidou.mybatisplus.core.exceptions.MybatisPlusException:Prohibition of table update operationatcom.baomidou.mybatisplus.core.toolkit.ExceptionUtils.mpe(ExceptionUtils.java:49)at com.baomidou.mybatisplus.core.toolkit.Assert.isTrue(Assert.java:38)at com.baomidou.mybatisplus.core.toolkit.Assert.notNull(Assert.java:72)atcom.baomidou.mybatisplus.extension.parsers.BlockAttackSqlParser.processUpdate(BlockAttackSqlParser.java:45)atcom.baomidou.mybatisplus.core.parser.AbstractJsqlParser.processParser(AbstractJsqlParser.java:92)atcom.baomidou.mybatisplus.core.parser.AbstractJsqlParser.parser(AbstractJsqlParser.java:67)atcom.baomidou.mybatisplus.extension.handlers.AbstractSqlParserHandler.sqlParser(AbstractSqlParserHandler.java:76)atcom.baomidou.mybatisplus.extension.plugins.SqlExplainInterceptor.intercept(SqlExplainInterceptor.java:63)at org.apache.ibatis.plugin.Plugin.invoke(Plugin.java:61)at com.sun.proxy. $Proxy70 .update(Unknown Source)atorg.apache.ibatis.session.defaults.DefaultSqlSession.update(DefaultSqlSession.java:197)... 41 more
@Bean
public PerformanceInterceptor performanceInterceptor(){
PerformanceInterceptor performanceInterceptor = new
PerformanceInterceptor();
performanceInterceptor.setMaxTime(100);
performanceInterceptor.setFormat(true);
return performanceInterceptor; }
Time : 11 ms - ID : com.lagou.mp.mapper.UserMapper.selectByIdExecute SQL :SELECTid,user_name,password,name,age,FROMtb_userWHEREid = 7
@Bean
public OptimisticLockerInterceptor optimisticLockerInterceptor() {
return new OptimisticLockerInterceptor();
}
ALTER TABLE `tb_user`
ADD COLUMN `version` int(10) NULL AFTER `email`;
UPDATE `tb_user` SET `version`='1';
第⼆步,为User实体对象添加version字段,并且添加@Version注解:
@Version
private Integer version;
@Test
public void testUpdate(){
User user = new User();
user.setAge(30);
user.setId(2L);
user.setVersion(1); //获取到version为1
int result = this.userMapper.updateById(user);
System.out.println("result = " + result);
}
main] [com.baomidou.mybatisplus.extension.parsers.BlockAttackSqlParser]-[DEBUG] Original SQL: UPDATE tb_user SET age = ?,version = ? WHERE id = ? AND version = ?[main] [com.baomidou.mybatisplus.extension.parsers.BlockAttackSqlParser]-[DEBUG] parser sql: UPDATE tb_user SET age = ?, version = ? WHERE id = ? ANDversion = ?[main] [org.springframework.jdbc.datasource.DataSourceUtils]-[DEBUG] FetchingJDBC Connection from DataSource[main] [org.mybatis.spring.transaction.SpringManagedTransaction]-[DEBUG] JDBCConnection [HikariProxyConnection@540206885 wrappingcom.mysql.jdbc.JDBC4Connection@27e0f2f5] will not be managed by Spring[main] [com.lagou.mp.mapper.UserMapper.updateById]-[DEBUG] == > Preparing:UPDATE tb_user SET age = ?, version = ? WHERE id = ? AND version = ?[main] [com.lagou.mp.mapper.UserMapper.updateById]-[DEBUG] == > Parameters:30 (Integer), 2 (Integer), 2 (Long), 1 (Integer)[main] [com.lagou.mp.mapper.UserMapper.updateById]-[DEBUG] < == Updates: 1[main] [org.mybatis.spring.SqlSessionUtils]-[DEBUG] Closing non transactionalSqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@30135202]result = 1
package com.lagou.mp.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import java.util.List;
public interface MyBaseMapper extends BaseMapper {
List findAll();
}
package com.lagou.mp.mapper;
import com.lagou.mp.pojo.User;
public interface UserMapper extends MyBaseMapper {
User findById(Long id);
}
package com.lagou.mp.sqlInjector;
import com.baomidou.mybatisplus.core.injector.AbstractMethod;
import com.baomidou.mybatisplus.core.injector.DefaultSqlInjector;
import java.util.List;
public class MySqlInjector extends DefaultSqlInjector {
@Override
public List getMethodList() {
List methodList = super.getMethodList();
methodList.add(new FindAll());
// 再扩充⾃定义的⽅法
list.add(new FindAll());
return methodList;
}
}
package com.lagou.mp.sqlInjector;
import com.baomidou.mybatisplus.core.enums.SqlMethod;
import com.baomidou.mybatisplus.core.injector.AbstractMethod;
import com.baomidou.mybatisplus.core.metadata.TableInfo;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.mapping.SqlSource;
public class FindAll extends AbstractMethod {
@Override
public MappedStatement injectMappedStatement(Class> mapperClass, Class
> modelClass, TableInfo tableInfo) {
String sqlMethod = "findAll";
String sql = "select * from " + tableInfo.getTableName();
SqlSource sqlSource = languageDriver.createSqlSource(configuration,
sql, modelClass);
return this.addSelectMappedStatement(mapperClass, sqlMethod,
sqlSource, modelClass, tableInfo);
}
}
/**
* ⾃定义SQL注⼊器
*/
@Bean
public MySqlInjector mySqlInjector(){
return new MySqlInjector();
}
@Test
public void testFindAll(){
List users = this.userMapper.findAll();
for (User user : users) {
System.out.println(user);
}
}
[main] [com.lagou.mp.mapper.UserMapper.findAll]-[DEBUG] == > Preparing: select* from tb_user[main] [com.lagou.mp.mapper.UserMapper.findAll]-[DEBUG] == > Parameters:[main] [com.lagou.mp.mapper.UserMapper.findAll]-[DEBUG] < == Total: 10
@TableField(fill = FieldFill.INSERT) //插⼊数据时进⾏填充
private String version;
public enum FieldFill {
9.2、编写MyMetaObjectHandler
9.3、测试
/**
* 默认不处理
*/
DEFAULT,
/**
* 插⼊时填充字段
*/
INSERT,
/**
* 更新时填充字段
*/
UPDATE,
/**
* 插⼊和更新时填充字段
*/
INSERT_UPDATE
}
package com.lagou.mp.handler;
import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;
@Component
public class MyMetaObjectHandler implements MetaObjectHandler {
@Override
public void insertFill(MetaObject metaObject) {
Object password = getFieldValByName("version", metaObject);
if(null == password){
//字段为空,可以进⾏填充
setFieldValByName("version", "123456", metaObject);
}
}
@Override
public void updateFill(MetaObject metaObject) {
}
}
@Test
public void testInsert(){
User user = new User();
user.setName("冰冰");
user.setAge(30);
user.setVersion(1);
int result = this.userMapper.insert(user);
System.out.println("result = " + result);
}
ALTER TABLE `tb_user`
ADD COLUMN `deleted` int(1) NULL DEFAULT 0 COMMENT '1代表删除,0代表未删除'
AFTER `version`;
@TableLogic
private Integer deleted;
# 逻辑已删除值(默认为 1)
mybatis-plus.global-config.db-config.logic-delete-value=1
# 逻辑未删除值(默认为 0)
mybatis-plus.global-config.db-config.logic-not-delete-value=0
@Test
public void testDeleteById(){
this.userMapper.deleteById(2L);
}
[main] [com.lagou.mp.mapper.UserMapper.deleteById]-[DEBUG] == > Preparing:UPDATE tb_user SET deleted = 1 WHERE id = ? AND deleted = 0[main] [com.lagou.mp.mapper.UserMapper.deleteById]-[DEBUG] == > Parameters:2 (Long)[main] [com.lagou.mp.mapper.UserMapper.deleteById]-[DEBUG] < == Updates: 1
@Test
public void testSelectById(){
User user = this.userMapper.selectById(2L);
System.out.println(user);
}
[main] [com.lagou.mp.mapper.UserMapper.selectById]-[DEBUG] == > Preparing:SELECT id,user_name,password,name,age,email,version,deleted FROM tb_user WHEREid = ? AND deleted = 0[main] [com.lagou.mp.mapper.UserMapper.selectById]-[DEBUG] == > Parameters:2 (Long)[main] [com.lagou.mp.mapper.UserMapper.selectById]-[DEBUG] < == Total: 0
4.0.0
org.springframework.boot
spring-boot-starter-parent
2.3.4.RELEASE
com.lagou
lagou-mp-generator
0.0.1-SNAPSHOT
lagou-mp-generator
Demo project for Spring Boot
11
org.springframework.boot
spring-boot-starter-test
test
com.baomidou
mybatis-plus-boot-starter
3.1.1
com.baomidou
mybatis-plus-generator
3.1.1
org.springframework.boot
spring-boot-starter-freemarker
mysql
mysql-connector-java
5.1.47
org.slf4j
slf4j-log4j12
org.springframework.boot
spring-boot-starter-web
org.projectlombok
lombok
true
org.springframework.boot
spring-boot-maven-plugin
package com.lagou.mp.generator;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
import com.baomidou.mybatisplus.core.exceptions.MybatisPlusException;
import com.baomidou.mybatisplus.core.toolkit.StringPool;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.generator.AutoGenerator;
import com.baomidou.mybatisplus.generator.InjectionConfig;
import com.baomidou.mybatisplus.generator.config.DataSourceConfig;
import com.baomidou.mybatisplus.generator.config.FileOutConfig;
import com.baomidou.mybatisplus.generator.config.GlobalConfig;
import com.baomidou.mybatisplus.generator.config.PackageConfig;
import com.baomidou.mybatisplus.generator.config.StrategyConfig;
import com.baomidou.mybatisplus.generator.config.TemplateConfig;
import com.baomidou.mybatisplus.generator.config.po.TableInfo;
import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;
import com.baomidou.mybatisplus.generator.engine.FreemarkerTemplateEngine;
/**
*
* mysql 代码⽣成器演示例⼦
*
*/
public class MysqlGenerator {
/**
*
* 读取控制台内容
*
*/
public static String scanner(String tip) {
Scanner scanner = new Scanner(System.in);
StringBuilder help = new StringBuilder();
help.append("请输⼊" + tip + ":");
System.out.println(help.toString());
if (scanner.hasNext()) {
String ipt = scanner.next();
if (StringUtils.isNotEmpty(ipt)) {
return ipt;
}
}
throw new MybatisPlusException("请输⼊正确的" + tip + "!");
}
/**
* RUN THIS
*/
public static void main(String[] args) {
// 代码⽣成器
AutoGenerator mpg = new AutoGenerator();
// 全局配置
GlobalConfig gc = new GlobalConfig();
String projectPath = System.getProperty("user.dir");
gc.setOutputDir(projectPath + "/src/main/java");
gc.setAuthor("lagou");
gc.setOpen(false);
mpg.setGlobalConfig(gc);
// 数据源配置
DataSourceConfig dsc = new DataSourceConfig();
dsc.setUrl("jdbc:mysql://127.0.0.1:3306/mp?
useUnicode=true&useSSL=false&characterEncoding=utf8");
// dsc.setSchemaName("public");
dsc.setDriverName("com.mysql.jdbc.Driver");
dsc.setUsername("root");
dsc.setPassword("root");
mpg.setDataSource(dsc);
// 包配置
PackageConfig pc = new PackageConfig();
pc.setModuleName(scanner("模块名"));
pc.setParent("com.lagou.mp.generator");
mpg.setPackageInfo(pc);
// ⾃定义配置
InjectionConfig cfg = new InjectionConfig() {
@Override
public void initMap() {
// to do nothing
}
};
List focList = new ArrayList<>();
focList.add(new FileOutConfig("/templates/mapper.xml.ftl") {
@Override
public String outputFile(TableInfo tableInfo) {
// ⾃定义输⼊⽂件名称
return projectPath + "/lagou-mpgenerator/src/main/resources/mapper/" + pc.getModuleName()
+ "/" + tableInfo.getEntityName() + "Mapper" +
StringPool.DOT_XML;
}
});
cfg.setFileOutConfigList(focList);
mpg.setCfg(cfg);
mpg.setTemplate(new TemplateConfig().setXml(null));
// 策略配置
StrategyConfig strategy = new StrategyConfig();
strategy.setNaming(NamingStrategy.underline_to_camel);
strategy.setColumnNaming(NamingStrategy.underline_to_camel);
//strategy.setSuperEntityClass("com.baomidou.mybatisplus.samples.generator.common.BaseEntity");
strategy.setEntityLombokModel(true);
//strategy.setSuperControllerClass("com.baomidou.mybatisplus.samples.generator.common.BaseController");
strategy.setInclude(scanner("表名"));
strategy.setSuperEntityColumns("id");
strategy.setControllerMappingHyphenStyle(true);
strategy.setTablePrefix(pc.getModuleName() + "_");
mpg.setStrategy(strategy);
// 选择 freemarker 引擎需要指定如下加,注意 pom 依赖必须有!
mpg.setTemplateEngine(new FreemarkerTemplateEngine());
mpg.execute();
}
}