1,简介
简称MP:是一款MyBatis的增强工具,在mybatis的基础上只做增强,不做改变,
为简化而生,提高工作效率
官网:https://baomidou.com/guide/
2,新建springboot项目
3,新建数据库user
4,所需要的依赖
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-jdbc</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <optional>true</optional> </dependency> <dependency> <groupId>com.baomidou</groupId> <artifactId>mybatis-plus-boot-starter</artifactId> <version>3.0.5</version> </dependency> <dependency> <groupId>com.h2database</groupId> <artifactId>h2</artifactId> <scope>runtime</scope> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency>
5,applicationContext.properties文件
#数据库连接基本参数 spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver spring.datasource.url=jdbc:mysql://localhost:3306/mybatis_plus?serverTimezone=GMT%2B8&useSSL=false&useUnicode=true&characterEncoding=utf8 spring.datasource.username=root spring.datasource.password=zhs03171812 #日志输出,使用默认的控制台输出 mybatis-plus.configuration.log-impl=org.apache.ibatis.logging.stdout.StdOutImpl #实现逻辑删除 #mybatis-plus.global-config.db-config.logic-not-delete-value=0 #逻辑未删除默认为0 #mybatis-plus.global-config.db-config.logic-delete-value=1 #逻辑已删除默认为1
6,在pojo的User类下
package com.example.demo.pojo; import com.baomidou.mybatisplus.annotation.*; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; import java.io.Serializable; import java.util.Date; @Data @NoArgsConstructor @AllArgsConstructor public class User implements Serializable { @TableId(type = IdType.AUTO) private long id; private String name; private Integer age; private String email; //通过该字段实现逻辑删除 // @TableLogic // private Integer deleted; //插入对象时所获取的时间 @TableField(fill = FieldFill.INSERT) private Date createTime; //更新时所获取的时间 @TableField(fill = FieldFill.INSERT_UPDATE) private Date updateTime; }
7,在mapper包下新建UserMapper类
package com.example.demo.mapper; import com.baomidou.mybatisplus.core.mapper.BaseMapper; import com.example.demo.pojo.User; import org.springframework.stereotype.Repository; @Repository public interface UserMapper extends BaseMapper<User> { }
8,在主程序DemoApplication中加入一个扫描的配置文件,这样mybatis-plus就已经整合进来了
9,由于时间是我后面加进来的,这里就先将配置handle配置好一起进行测试了。在handle包下新建一个 MyMetaObjectHandler 类并实现一个 MetaObjectHandler 接口。这样的话我们在插入对象的时候或者修改对象的时候就可以设置时间了,而且时间并没有走国际化,但是里面有插件自动帮我们做成
package com.example.demo.handler; import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler; import lombok.extern.slf4j.Slf4j; import org.apache.ibatis.reflection.MetaObject; import org.springframework.stereotype.Component; import java.util.Date; @Slf4j @Component public class MyMetaObjectHandler implements MetaObjectHandler { @Override public void insertFill(MetaObject metaObject) { log.info("插入开始"); //String fieldName, Object fieldVal, MetaObject metaObject //设置插入的时间 this.setFieldValByName("createTime",new Date(),metaObject); //设置更新的时间 this.setFieldValByName("updateTime",new Date(),metaObject); } @Override public void updateFill(MetaObject metaObject) { log.info("更新开始"); this.setFieldValByName("updateTime",new Date(),metaObject); } }
10,分页查询,在config配置包下新建一个MybatisPlusConfig类,并在这个类下实例一个分页插件的对象
package com.example.demo.config; import com.baomidou.mybatisplus.core.injector.ISqlInjector; import com.baomidou.mybatisplus.extension.injector.LogicSqlInjector; 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 //扫描mapper文件夹 @MapperScan("com.example.demo.mapper") public class MybatisPlusConfig { //分页插件 @Bean public PaginationInterceptor paginationInterceptor() { PaginationInterceptor paginationInterceptor = new PaginationInterceptor(); // 设置请求的页面大于最大页后操作, true调回到首页,false 继续请求 默认false // paginationInterceptor.setOverflow(false); // 设置最大单页限制数量,默认 500 条,-1 不受限制 // paginationInterceptor.setLimit(500); // 开启 count 的 join 优化,只针对部分 left join //paginationInterceptor.setCountSqlParser(new JsqlParserCountOptimize(true)); return paginationInterceptor; } //逻辑查询插件 // @Bean // public ISqlInjector sqlInjector(){ // return new LogicSqlInjector(); // } }
11,进行代码测试,看是否能够连接数据库,并且能否实现数据的增删改查
package com.example.demo; import com.baomidou.mybatisplus.extension.plugins.pagination.Page; import com.example.demo.mapper.UserMapper; import com.example.demo.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; @SpringBootTest class DemoApplicationTests { @Autowired private UserMapper userMapper; @Test void contextLoads() { //查询全部用户,里面的参数wrapper为查询条件,这里设置为空 List<User> users = userMapper.selectList(null); users.forEach(e-> System.out.println(e)); } //插入 @Test public void Insert(){ //由于数据库中设置自增,可以不需要插入id User user = new User(); user.setName("wangwu"); user.setAge(23); user.setEmail("127694@qq.com"); userMapper.insert(user); } //更新 @Test public void Update(){ User user = new User(); user.setId(6L); user.setName("zhenghuisheng"); user.setAge(20); user.setEmail("1652724084@qq.com"); int i = userMapper.updateById(user); System.out.println(i); } @Test //查询,通过id查询 public void toSelete(){ User user = userMapper.selectById(1); System.out.println(user); } @Test //可以通过多个id进行查询 public void toSeletes(){ List<User> users = userMapper.selectBatchIds(Arrays.asList(1L,2L,3L,4L,5L)); users.forEach(e-> System.out.println(e)); } @Test //可以通过条件进行查询 public void toSeleteMap(){ Map<String,Object> map = new HashMap<>(); map.put("name","zhenghuisheng"); List<User> users = userMapper.selectByMap(map); users.forEach(e-> System.out.println(e)); } //删除 @Test public void toDelete(){ userMapper.deleteById(3L); } @Test //批量删除 public void toDeletes(){ int i = userMapper.deleteBatchIds(Arrays.asList(1L,2L, 3L, 4L, 5L)); System.out.println("删除成功!"); } @Test //测试分页查询 public void testPage(){ //第一个参数为要查询的当前页,第二个参数为要查询的数量大小 Page<User> page = new Page<>(1,5); //设置分页查询,参数wrapper为查询条件,这里设置为空 userMapper.selectPage(page,null); page.getRecords().forEach(e-> System.out.println(e)); } }
12,从头到尾都可以发现自己并没有写一句sql语句,因此需要开启日志功能,在applicationContext.propertiesq文件下加入。在测试阶段,就可以通过日志查看我们代码所对应的sql语句了
#日志输出,使用默认的控制台输出 mybatis-plus.configuration.log-impl=org.apache.ibatis.logging.stdout.StdOutImpl
13,再补充一点条件构造器,即wrapper,官网都写的明明白白,在这里进行测试两个
package com.example.demo; import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; import com.example.demo.mapper.UserMapper; import com.example.demo.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.List; @SpringBootTest public class WrapperTest { @Autowired private UserMapper userMapper; @Test //区间查询,查询年龄在20到30岁之间的值 void contextLoads() { QueryWrapper<User> queryWrapper = new QueryWrapper<>(); queryWrapper.between("age", 20, 30); List<User> users = userMapper.selectList(queryWrapper); users.forEach(e-> System.out.println(e)); } //模糊查询 @Test public void seleteLike(){ QueryWrapper<User> queryWrapper = new QueryWrapper<>(); //name这个字段中不包含t的所有名字 queryWrapper.notLike("name","t"); List<User> users = userMapper.selectList(queryWrapper); users.forEach(e-> System.out.println(e)); } }