MyBatis-Plus快速入门

1. MyBatis-Plus基本操作

MyBatis-Plus(简称 MP)是一个 MyBatis的增强工具,在 MyBatis 的基础上只做增强不做改变,为 简化开发、提高效率而生,简单来说通过配置自动写sql语句

内置代码生成器:采用代码或者Maven插件可以快速生成Mapper Model Service Controller

支持多种数据库:Mysql Oracle等


CREATE DATABASE `mybatis_plus` /*!40100 DEFAULT CHARACTER SET utf8mb4 */;
use `mybatis_plus`;
CREATE TABLE `user` (
`id` bigint(20) NOT NULL COMMENT '主键ID',
`name` varchar(30) DEFAULT NULL COMMENT '姓名',
`age` int(11) DEFAULT NULL COMMENT '年龄',
`email` varchar(50) DEFAULT NULL COMMENT '邮箱',
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

因为默认使用雪花算法,所以主键使用Bigint类型的主键id

spring:
  datasource:
    type: com.zaxxer.hikari.HikariDataSource
    hikari:
      password: 1234
      username: root
      driver-class-name: com.mysql.cj.jdbc.Driver
      jdbc-url: jdbc:mysql://localhost:3306/mybatis_plus?useUnicode=true&characterEncoding=utf8&useSSL=false&serverTimezone=Asia/Shanghai&tinyInt1isBit=false
    url: jdbc:mysql://localhost:3306/mybatis_plus?useUnicode=true&characterEncoding=utf8&useSSL=false&serverTimezone=Asia/Shanghai&tinyInt1isBit=false

mybatis-plus:
#  这东西报错  config-location 和 configuration 不能同时存在
#  config-location: classpath:mybatis-config.xml
  mapper-locations: classpath:plusConfig\*.xml
  configuration:
    log-impl: org.apache.ibatis.logging.stdout.StdOutImpl

@SpringBootTest
class DemoApplicationTests {


    @Autowired
    UserMapper userMapper;

    @Test
    public void testUserMapper(){
        //通过条件构造器查询一个List集合,若没有调价,则可以设置null为参数
        List<User> users = userMapper.selectList(null);
        users.forEach(System.out::println);
    }

    @Test
    public void testInsert(){
        User user = new User();
        user.setAge(1);
        user.setName("123");
        user.setEmail("daada@qq.com");
        int insert = userMapper.insert(user);
        System.out.println(insert);
    }

    @Test
    public void testUpdate(){
        //根据id进行update
        //如果填入的值为null 就不进行修改
        userMapper.updateById(new User(1L,"1@1323",1,"222@qq.com"));
    }

    @Test
    public void testDelete(){

        int i = userMapper.deleteById(1L);
        //根据写map的键值对为条件
        Map map = new HashMap();
        //对name=Shimada Yamato的行进行删除
        map.put("name","Shimada Yamato");
        userMapper.deleteByMap(map);

    }

}

上面是通用的增删改查操作

2. 通用Service

Service CRUD 封装IService接口,进一步封装 CRUD 采用 get 查询单行 remove 删 除 list 查询集合 page 分页 前缀命名方式区分 Mapper 层避免混淆。

里面提供一个ServiceImpl 实现了IService 接口,但是一般不会用service层是高度自定义化的,所以封装的ServiceImpl无法满足定制化需求 我们需要自己定义一个Service

我们需要继承ServiceImpl 并且实现自己写的Service接口,这样又能使用封装工具,又能满足定制化需求

public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {
}

测试用例

@SpringBootTest
public class MybatisPlusServiceTest {
    @Autowired
    private UserService userService;

    @Test
    public void testGetCount(){
        //查询总记录数
        long count = userService.count();
        System.out.println(count);
        System.out.println("总记录数"+count);
        //进行批量添加
        ArrayList<User> users = new ArrayList<>();
        users.add(new User());
        users.add(new User());
        boolean b = userService.saveBatch(users);
        System.out.println(b);


    }


}

3. 常用注解

  • @TableName("user")

如果pojo/bean中的类名和数据库的名字不一样,可以通过@TableName("t_user")属性进行修改,指定数据库中的表名

mybatis-plus:
  global-config:
    db-config:
      table-prefix: 

也可以通过配置文件,设置统一的表名前缀

  • @TableId

设置其他属性作为表的主键,默认使用id作为主键,通过雪花算法进行赋值

在属性上进行标明

@TableId存在两个属性Value type

通过设置Value属性可以改变属性映射主键的名称

通过设置type属性可以改变id自增策略 Idtype为枚举类型

NONE为雪花算法 AUTO为自增

@Data
@AllArgsConstructor
@NoArgsConstructor
@ToString
@EqualsAndHashCode
@TableName("user")
public class User {
    @TableId(Value="uid",type=Idtype.NONE)
    private Long id;
    private String name;
    private Integer age;
    private String email;
}

  • @TableField

使用@TableField对属性所映射的字段名进行映射

  • @TableLogic

进行逻辑删除,Mybatis_Plus将设置的属性标记为被删除状态,但是数据库仍然可以看到,Mybatis_Plus的查询功能看不到

3. 条件构造器

使用条件构造器需要new 一个QueryWrapper

对QueryWrapper对象进行操作进行条件配置

@SpringBootTest
public class MybatisPlusWrapperTest {

    @Autowired
    private UserService userService;

    @Test
    public void test01(){
        QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
        userQueryWrapper.like("name","a")
                .between("age",20,100)
                .isNotNull("email").orderByAsc("age");
        List<User> list = userService.list(userQueryWrapper);
        list.forEach(System.out::println);

    }
    @Test
    public void test02(){
        QueryWrapper<User> userQueryWrapper = new QueryWrapper<User>();
        userQueryWrapper.ge(true,"age",900);
        List<User> list = userService.list(userQueryWrapper);
        list.sort(new Comparator<User>() {
            @Override
            public int compare(User o1, User o2) {
                return o1.getAge()-o2.getAge();
            }
        });
        list.forEach(System.out::println);
    }

    @Test
    public void test03(){
        String name = "Sun Jiehong";
        LambdaQueryWrapper<User> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.like(StringUtils.isNotBlank(name),User::getName,"Sun");
        List<User> list = userService.list(lambdaQueryWrapper);
        System.out.println(list);


    }


}

4. 分页查询

  • 配置分页拦截器
@Configuration
public class MybatisPlusConfig {
    @Bean
    public MybatisPlusInterceptor mybatisPlusInterceptor(){
        MybatisPlusInterceptor mybatisPlusInterceptor = new MybatisPlusInterceptor();
        mybatisPlusInterceptor.addInnerInterceptor(new PaginationInnerInterceptor());
        return mybatisPlusInterceptor;
    }
}
  • 进行查询
@SpringBootTest
public class MybatisPlusPlugins {
    @Autowired
    private UserMapper userMapper;

    @Test
    public void test01(){
        Page<User> Page = new Page<User>(2,3);

        Page<User> userPage = userMapper.selectPage(Page, null);
        System.out.println(userPage.getPages());
    }


}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值