学习笔记-Mybatis-Plus

mybatis-plus

新建工程

  • pom.xml
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter</artifactId>
</dependency>
<!--mysql驱动-->
<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <scope>runtime</scope>
</dependency>
<!--mybatis plus 启动器-->
<dependency>
    <groupId>com.baomidou</groupId>
    <artifactId>mybatis-plus-boot-starter</artifactId>
    <version>3.5.1</version>
</dependency>
<!--lombok 简化实体开发-->
<dependency>
    <groupId>org.projectlombok</groupId>
    <artifactId>lombok</artifactId>
    <optional>true</optional>
</dependency>
  • application.properties
spring.datasource.type=com.zaxxer.hikari.HikariDataSource
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/xxx?characterEncoding=utf-8&userSSL=false&serverTimezone=GMT%2B8
spring.datasource.username=xxxx
spring.datasource.password=xxxx
# 加入日志配置
mybatis-plus.configuration.log-impl=org.apache.ibatis.logging.stdout.StdOutImpl
# 设置mybatis-plus全局配置
# 设置表前缀
mybatis-plus.global-config.db-config.table-prefx=t_
# 设置统一主键生成策略
mybatis-plus.global-config.id-type=auto
# 设置类型别名
mybatis-plus.type-aliases-package=xxx.xxx.pojo
  • Application
@SpringBootApplication
// 扫描mapper接口包
@MapperScan("xxx.xxx.mapper")
public class Application{
    public static void main(String[] agrs){
        SpringApplication.run(Application.class,args);
    }
}
  • xxx.xxx.pojo.User
@Data
@TableName("t_user")
public class User{
    @TabledId
    private Long id;
    private String name;
    private Integer age;
    private String email;
}
  • xxx.xxx.mapper.UserMapper
@Repository
public interface UserMapper extends BaseMapper<User>{
    
}
  • 测试
@Autowired
private UserMapper userMapper;

public void testSelectList(){
    // 通过条件构造器查询list集合,没有条件传null
    List<User> list = userMapper.selectList(null);
    list.forEach(System.out::println);
}

BaseMapper

  • insert(T entity)
  • deleteById()
  • deleteByMap(Map<String,Object> map)
  • deleteBatchIds(Collection<?> ids)
  • updateById(T entity)
  • selectById()
  • selectBatchIds(Collection<?> ids)
  • selectByMap(Map<String,Object> map)
  • selectList(Wrapper wrapper)

条件构造器

  • Wrapper:条件构造器
    • AbstractWrapper
      • QueryWrapper:查询条件封装
      • UpdateWrapper:update条件封装
      • AbstractLambdaWrapper
        • LambdaQueryWrapper
        • LambdaUpdateWrapper
QueryWrapper
QueryWrapper<User> queryWrapper = new QueryWrapper<>();
queryWrapper.like("user_name","a")
    .between("age",20,30)
    .isNotNull("email")
    .orderByDesc("age")
    .orderByAsc("id");
userMapper.selectList(queryWrapper);
根据条件delete
QueryWrapper<User> queryWrapper = new QueryWrapper<>();
queryWrapper.isNull("email");
userMapper.delete(queryWrapper);
根据条件update
QueryWrapper<User> queryWrapper = new QueryWrapper<>();
queryWrapper.gt("age",20)   // 年龄大于20
    .like("user_name","a")  // 模糊查询
    .or()
    .isNull("email");
User user = new User();
user.setName("xxx");
user.setEmail("xxx@xxx.com");
userMapper.update(user,queryWrapper);
查询优先级
// 名字包含a并且(年龄大于20或emial为null)
QueryWrapper<User> queryWrapper = new QueryWrapper<>();
queryWrapper.like("user_name","a")
    .and(i->i.gt("age",20)
        .or()
        .isNull("email")
    ) ;
User user = new User();
user.setName("xxx");
user.setEmail("xxx@xxx.com");
userMapper.update(user,queryWrapper);
组装查询field
QueryWrapper<User> queryWrapper = new QueryWrapper<>();
queryWrapper.select("user_name","age","email");
userMapper.selectMaps(queryWrapper);
组装子查询
QueryWrapper<User> queryWrapper = new QueryWrapper<>();
queryWrapper.inSql("uid","select uid from t_user where uid<=1000");
List<User> list = userMapper.selectList(queryWrapper);
condition组装
// 满足条件才组装
String username = "";
Integer ageBegin = null;
Integer ageEnd = 30;
QueryWrapper queryWrapper = new QueryWrapper();
queryWrapper.like(StringUtils.isNotBlank(username),"user_name",username)
    .ge(ageBegin!=null,"age",ageBegin)
    .le(ageEnd!=null,"age",ageEnd);
List<User> list = userMapper.selectList(queryWrapper);
UpadteyWrapper
UpdateWrapper<User> updateWrapper = new UpdateWrapper<>();
updateWrapper.like("user_name","a")
    .and(i->i.gt("age",20).or().isNull("email"));
updateWrapper.set("user_name","xxx")
    .set("email","xxx");
userMapper.update(null,updateWrapper);
LambdaQueryWrapper
// 自动获取属性对应字段名称
String username = "";
Integer ageBegin = null;
Integer ageEnd = 30;
LambdaQueryWrapper queryWapper = new LambdaQueryWrapper();
queryWrapper.like(StringUtils.isNotBlank(username),User::getName,username)
    .ge(ageBegin!=null,User::getAge,ageBegin)
    .le(ageEnd!=null,,User::getAge,ageEnd);
List<User> list = userMapper.selectList(queryWrapper);
LambdaUpdateWrapper
// 自动获取属性对应字段名称
String username = "";
Integer ageBegin = null;
Integer ageEnd = 30;
LambdaUpdateWrapper updateWapper = new LambdaUpdateWrapper();
updateWapper.like(User::getName,"a")
   .and(i->i.gt(User::getAge,20).or().isNull(User::getEmail));
updateWrapper.set(User::getName,"xxx")
    .set(User::getEmail,"xxx");
userMapper.update(null,updateWrapper);

自定义功能

  • xxx.xxx.mapper.UserMapper
@Repository
public interface UserMapper extends BaseMapper<User>{
    Map<String,Object> selectMapById(Long id);
    
}
  • resources/mapper/UserMapper.xml
<? xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
    PUBLIC "-//mybatis.org/DTD Mapper 3.0//EN"
    "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="xxx.xxx.mapper.UserMapper">
    <select id="selectMapById" resultType="Map">
        select id,name,age,email from user where id=#{id}
    </select>
</mapper>

通用Servie接口

  • xxx.xxx.service.UserService
    • saveBatch(Collection list)
public interface UserService extends IService<User>{
    
}
  • xxx.xxx.service.impl.UserServiceImpl
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper,User> implements UserService{
    
}

test

@Autowired
private UserService userService;

public void test(){
    long count = userService.count();
}

注解

  • @TableName(“user”)
    • 设置实体类对应表
  • @TableId(value=“”,type=IdType.AUTO)
    • 将属性对应的字段指定为主键
    • value
      • 指定主键的字段
    • type
      • 主键生成策略
      • IdType.AUTO:自增
      • IdType.ASSIGN_ID:默认,雪花算法
  • @TableField
  • @TableLogic
    • 逻辑删除
    • isDeleted/is_deleted

分页

  • config.MybatisPlusConfig
@Configuration
@MapperScan("xxx.xxx.mapper")
public class MyBatisPlusConfig{
    @Bean
    public MyBatisPlusInterceptor MybatisPlusInterceptor(){
        MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
        interceptor.addInnerInterceptor(new PaginationInterceptor(DbType.MYSQL));
        return interceptor;
    }
}
int current = 1;
int size = 3;
Page<User> page = new Page(current,size);
userMapper.selectPage(page,null)
  • Page
    • page.getRecords()
      • 获取当前页数据
    • page.getCurrent()
    • page.getSize()
    • page.getPages()
      • 总页数
    • page.getTotal()
    • page.hasNext()
      • 是否有下一页
    • page.hasPrevious()
      • 是否有上一页

自定义方法的分页

  • xxx.xxx.mapper.UserMapper
@Repository
public interface UserMapper extends BaseMapper<User>{
   Page<User> selectPageVo(@Param("page")Page<User> page,@Param("age")Integer age);
}
  • resources/mapper/UserMapper.xml
<? xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
    PUBLIC "-//mybatis.org/DTD Mapper 3.0//EN"
    "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="xxx.xxx.mapper.UserMapper">
    <select id="selectPageVo" resultType="xxx.xxx.pojo.User">
        select * from user where age>#{age}
    </select>
</mapper>

乐观锁

  • config.MybatisPlusConfig
@Configuration
@MapperScan("xxx.xxx.mapper")
public class MyBatisPlusConfig{
    @Bean
    public MyBatisPlusInterceptor MybatisPlusInterceptor(){
        MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
        // 添加分页插件
        interceptor.addInnerInterceptor(new PaginationInterceptor(DbType.MYSQL));
        // 添加乐观锁插件
        interceptor.addInnerInterceptor(new OptimisticLockerInnerInterceptor());
        return interceptor;
    }
}
  • xxx.xxx.pojo.User
// 实体类字段添加
// 标识乐观锁版本号
@Version
private Integer version;

通用枚举

  • application.properties
# 扫描枚举所在包
mybatis-plus.type-enums-package=xxx.xxx.enums
  • xxx.xxx.enums.SexEnum
@Getter
public enum SexEnum{
    MALE(1,"男")FEMALE(2,"女")// 将注解标识的值存入数据库
    @EnumValue
    private Integer sex;
    private String sexName;
    
    SexEnum(Integer sex,String sexName){
        this.sex = sex;
        this.sexName  = sexName;
    }
}
  • xxx.xxx.pojo.User
// 可以在实体类中使用
private SexEnum sex;

代码生成器

  • pom.xml
<dependency>
    <groupId>com.baomidou</groupId>
    <artifactId>mybatis-plus-generator</artifactId>
    <version>3.5.1</version>
</dependency>
<dependency>
    <groupId>org.freemarker</groupId>
    <artifactId>freemarker</artifactId>
    <version>2.3.31</version>
</dependency>
public static void main(String[] args){
    FastAutoGenerator.create("url","username","password")
        .globalConfig(builder -> {
            builder.author("xxx")           // 设置作者
                // .enableSwagger()         // 开启Swagger模式
                .fileOverride()             // 覆盖已有文件
                .outputDir("/data");    // 指定输出地点 
        })
        .packageConfig(builder -> {
            builder.parent("xxx.xxx")       // 设置父包名
                .moduleName("xxx")          //模块名
                // 设置mapperXml生成路径
                .pathInfo(Collections.singletonMap(OutputFile.mapperXml,"/data/mapper")); 
        })
        .strategyConfig(builder -> {
            builder.addInclude("t_user")        // 设置需要生成的表名
                .addTablePrefix("t_", "c_");    // 设置过滤表前缀
        })
        .templateEngine(new FreemarkerTemplateEngine()) // 使用Freemarker引擎模板,默认的是Velocity引擎模板
        .execute();
}

多数据源

  • pom.xml
<dependency>
    <groupId>com.baomidou</groupId>
    <artifactId>dynamic-datasource-spring-boot-starter</artifactId>
    <version>3.5.0</version>
</dependency>
  • application.properties
# 默认数据源
spring.datasource.dynamic.primary=master
# 是否严格模式
spring.datasource.dynamic.strict=false
spring.datasource.dynamic.datasource.master.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.dynamic.datasource.master.url=jdbc:mysql://localhost:3306/xxx?characterEncoding=utf-8&userSSL=false
spring.datasource.dynamic.datasource.master.username=xxxx
spring.datasource.dynamic.datasource.master.password=xxxx

spring.datasource.dynamic.datasource.slave_1.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.dynamic.datasource.slave_1.url=jdbc:mysql://localhost:3306/xxx?characterEncoding=utf-8&userSSL=false
spring.datasource.dynamic.datasource.slave_1.username=xxxx
spring.datasource.dynamic.datasource.slave_1.password=xxxx
  • xxx.xxx.service.UserService
public interface UserService extends IService<User>{
    
}
  • xxx.xxx-service.impl.UserServiceImpl
@Service
// 指定操作的数据源
// 可以加到方法上,实现主从数据源
@DS("master")
//@DS("slave_1")
public class UserServiceImpl extends ServiceImpl<UserMapper,User> implemnts UserService{
    
}
@MapperScan("xxx.xxx.mapper")

插件

  • MybatisX
    • xml与mapper跳转
    • 代码自动生成
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值