MybatisPlus入门
(跟着狂神老师学习的MybatisPlus)
MybatisPlus是什么?它与Mybatis有什么联系?
MybatisPlus就是Mybatis的加强版,也可以说他们是互相配合使用的。MybatisPlus简化了Crud,而且还可以自动生成代码,不需要我们重新去写mapper.xml文件,我们只需要重写一下Wrapper就可以了。
MybatisPlus的配置环境
(还需要配置datasource的)
1.配置好环境配置
2.导入jar
3.创建mapper继承BaseMapper
4.创建pojo
5.加入注解MapperScan在主类上面
6.配置好datasource文件
7.测试启动
代码(配置文件)
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/mybatisplus?useUnicode=true&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC
spring.datasource.username=root
spring.datasource.password=123456
mybatis-plus.configuration.log-impl=org.apache.ibatis.logging.stdout.StdOutImpl
代码(UserMapper)
@Repository
public interface UserMapper extends BaseMapper<User> {
}
代码(依赖)
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.0.5</version>
</dependency>
<!-- lombok-->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.16</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.47</version>
</dependency>
代码(test)
@Test
void contextLoads() {
List<User> users = userMapper.selectList(null);
users.forEach(System.out::println);
}
MybatisPlus的重要特性
- 各种插件(分页插件、乐观锁插件、自动填充)
首先需要说说的是如何导入插件,其实很简单只需要创建一个Config类,然后注入Bean就可以了,接下来就是自己设置一下就好了。
简单讲讲乐观锁,乐观锁其实就是在修改数据之前都不会上锁,直到修改的时候。这样会出现的弊端就是,如果这个时候有别的线程插队,它就会没办法再修改了。而在数据库里面的具体实现就是version,每次修改都会看看version是不是OldVersion如果是就能修改,并且version++,如果不是就没办法修改,如果有人插队了version修改了,那么这些语句就不会生效。
代码(插件实现)
@EnableTransactionManagement
@Configuration
public class MybatisPlusConfig {
@Bean
public MybatisPlusInterceptor optimisticLockerInnerInterceptor(){
MybatisPlusInterceptor interceptor=new MybatisPlusInterceptor();
interceptor.addInnerInterceptor(new OptimisticLockerInnerInterceptor());
interceptor.addInnerInterceptor(new PaginationInnerInterceptor());
return interceptor;
}
}
代码(插件实现的时候pojo需要的注释,这里的TableFill其实就是填充时间)
@Data
@AllArgsConstructor
@NoArgsConstructor
public class User {
@TableId(type=IdType.AUTO)
private int id;
private String name;
private int age;
private String email;
@Version
private int version;
@TableLogic
private Integer deleted;
@TableField(fill = FieldFill.INSERT_UPDATE)
private Date createTime;
@TableField(fill = FieldFill.INSERT_UPDATE)
private Date updateTime;
}
-
简化crud
我们不需要写mapper.xml,只需要Mapper接口实现了BaseMapper接口就可以了,然后就能使用这个类的方法。它能够帮我们实现增删改查,不需要我们写语句。
代码(举例)
@Test
void contextLoads() {
List<User> users = userMapper.selectList(null);
users.forEach(System.out::println);
}
@Test
void insert(){
User user=new User();
user.setName("帅哥3");
user.setAge(6);
user.setEmail("shuaige@qq.com");
userMapper.insert(user);
}
@Test
void update(){
User user=new User();
user.setId(8);
user.setName("请叫我好人");
user.setAge(6);
user.setEmail("shuaige@qq.com");
int i = userMapper.updateById(user);
System.out.println(i);
}
-
逻辑删除
逻辑删除其实就是相当于是回收站,我们可以增加一个deleted字段在数据库上面,如果删除了就是1,如果没有删除就设置为0。也就是说我们并不是真正地删除,而是通过调整deleted来删除,但是这个属性需要加上注解@TableLogic。并且配置一下文件。下面给出代码
代码(配置文件(官方文档的))
mybatis-plus:
global-config:
db-config:
logic-delete-field: flag # 全局逻辑删除的实体字段名(since 3.3.0,配置后可以忽略不配置步骤2)
logic-delete-value: 1 # 逻辑已删除值(默认为 1)
logic-not-delete-value: 0 # 逻辑未删除值(默认为 0)
代码(pojo)
@TableLogic
private Integer deleted;
-
代码自动生成
这些代码都是可以通过MybatisPlus的功能进行实现的。首先就是环境配置
①导入mybatis-plus-generator
②配置一下我们要生成什么(官方文档)
代码(test)
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("我是帅哥");
gc.setOpen(false);
gc.setFileOverride(false);//是否覆盖
gc.setServiceName("%sService");//去掉Service的I前缀
gc.setDateType(DateType.ONLY_DATE);
gc.setIdType(IdType.ID_WORKER);
mpg.setGlobalConfig(gc);
//配置数据库
DataSourceConfig dsc = new DataSourceConfig();
dsc.setUrl("jdbc:mysql://localhost:3306/mybatisplus?useUnicode=true&useSSL=false&characterEncoding=utf8");
// dsc.setSchemaName("public");
dsc.setDriverName("com.mysql.jdbc.Driver");
dsc.setUsername("root");
dsc.setPassword("123456");
mpg.setDataSource(dsc);
// 设置包
PackageConfig pc = new PackageConfig();
pc.setModuleName("blog");//你的存储包名
pc.setParent("com.kuang.xing");//你要存储包的位置
//包里面的东西
pc.setEntity("entity");
pc.setController("controller");
pc.setService("service");
mpg.setPackageInfo(pc);
//设置pojo的创建策略
StrategyConfig strategy = new StrategyConfig();
strategy.setInclude("user");
strategy.setNaming(NamingStrategy.underline_to_camel);
strategy.setColumnNaming(NamingStrategy.underline_to_camel);
strategy.setEntityLombokModel(true);
//逻辑删除
strategy.setLogicDeleteFieldName("deleted");
//自动填充,创建更新时间
TableFill gmtCreate=new TableFill("gmt_create", FieldFill.INSERT);
TableFill gmtModified=new TableFill("gmt_update",FieldFill.UPDATE);
ArrayList<TableFill> list=new ArrayList<>();
list.add(gmtCreate);
list.add(gmtModified);
strategy.setTableFillList(list);
//乐观锁
strategy.setVersionFieldName("version");
strategy.setRestControllerStyle(true);
strategy.setControllerMappingHyphenStyle(true);
mpg.setStrategy(strategy);
//执行
mpg.execute();
}
-
条件查询
在这个地方应该如何实现条件查询呢?MybatisPlus给我们提供了一个QueryWrapper类进行对条件的限定。其实也可以使用HashMap,但是HashMap只能够执行等值的条件查询,范围这些,子查询都没办法实现。但是QeuryWrapper就可以实现这些东西。这里有非常多的实例,我给出一些,其它可以通过查官方文档就可以了。
代码(test)
//查询name和email不为空的,而且年龄大于13的
@Test
public void test1(){
QueryWrapper<User> wrapper=new QueryWrapper<>();
wrapper
.isNotNull("name")
.isNotNull("email")
.ge("age",13);
List<User> users = userMapper.selectList(wrapper);
users.forEach(System.out::println);
}
//查询年龄在21到24的
@Test
public void test3(){
QueryWrapper<User> wrapper=new QueryWrapper<>();
wrapper.between("age",21,24);
List<User> users = userMapper.selectList(wrapper);
users.forEach(System.out::println);
}
//模糊查询
@Test
public void fuzzyQuery(){
QueryWrapper<User> wrapper=new QueryWrapper<>();
wrapper
.notLike("name","e")
.likeRight("name","帅");
List<User> users = userMapper.selectList(wrapper);
users.forEach(System.out::println);
}