mybatis plus学习笔记(1)

1.介绍

可以从官网看到介绍

https://mybatis.plus/guide/#%E7%89%B9%E6%80%A7

下面我们先无脑使用其功能,不考虑其是如何实现的,例子都是官方的

2.第一个例子

由于例子采用了spring boot start以及数据采用了h2,所以先略过此部分,直接使用,很无脑

mybatis plus学习笔记(1)_第1张图片

代码示例1

@Data
public class User {
    private Long id;
    private String name;
    private Integer age;
    private String email;
}

public interface UserMapper extends BaseMapper {

}

@RunWith(SpringRunner.class)
@SpringBootTest
public class SampleTest {

    @Resource
    private UserMapper userMapper;

    @Test
    public void testSelect() {
        System.out.println(("----- selectAll method test ------"));
        List userList = userMapper.selectList(null);
        Assert.assertEquals(5, userList.size());
        userList.forEach(System.out::println);
    }
}

1.定义了一个User实体类
2.定义一个继承自BaseMapper 的UserMapper映射类
3.调用UserMapper相关查询方法

就是这么简单,有点类似JPA的感觉

3.CRUD

只需要调用BaseMapper相关方法即可

public class SampleTest {

    @Resource
    private UserMapper mapper;

    @Test
    public void aInsert() {
        User user = new User();
        user.setName("小羊");
        user.setAge(3);
        user.setEmail("[email protected]");
        assertThat(mapper.insert(user)).isGreaterThan(0);
        // 成功直接拿会写的 ID
        assertThat(user.getId()).isNotNull();
    }


    @Test
    public void bDelete() {
        assertThat(mapper.deleteById(3L)).isGreaterThan(0);
        assertThat(mapper.delete(new QueryWrapper()
                .lambda().eq(User::getName, "Sandy"))).isGreaterThan(0);
    }


    @Test
    public void cUpdate() {
        assertThat(mapper.updateById(new User().setId(1L).setEmail("[email protected]"))).isGreaterThan(0);
        assertThat(mapper.update(new User().setName("mp"),
                Wrappers.lambdaUpdate()
                        .set(User::getAge, 3)
                        .eq(User::getId, 2))).isGreaterThan(0);
    }


    @Test
    public void dSelect() {
        assertThat(mapper.selectById(1L).getEmail()).isEqualTo("[email protected]");
        User user = mapper.selectOne(new QueryWrapper().lambda().eq(User::getId, 2));
        assertThat(user.getName()).isEqualTo("mp");
        assertThat(user.getAge()).isEqualTo(3);
    }
}

4.条件构造器

即构造一个QueryWrapper对象,直接一点可以理解为拼接sql语句

    @Test
    public void tests() {
        System.out.println("----- 普通查询 ------");
        List plainUsers = userMapper.selectList(new QueryWrapper().eq("role_id", 2L));
        List lambdaUsers = userMapper.selectList(new QueryWrapper().lambda().eq(User::getRoleId, 2L));
        Assert.assertEquals(plainUsers.size(), lambdaUsers.size());
        print(plainUsers);

        System.out.println("----- 带子查询(sql注入) ------");
        List plainUsers2 = userMapper.selectList(new QueryWrapper()
                .inSql("role_id", "select id from role where id = 2"));
        List lambdaUsers2 = userMapper.selectList(new QueryWrapper().lambda()
                .inSql(User::getRoleId, "select id from role where id = 2"));
        Assert.assertEquals(plainUsers2.size(), lambdaUsers2.size());
        print(plainUsers2);

        System.out.println("----- 带嵌套查询 ------");
        List plainUsers3 = userMapper.selectList(new QueryWrapper()
                .nested(i -> i.eq("role_id", 2L).or().eq("role_id", 3L))
                .and(i -> i.ge("age", 20)));
        List lambdaUsers3 = userMapper.selectList(new QueryWrapper().lambda()
                .nested(i -> i.eq(User::getRoleId, 2L).or().eq(User::getRoleId, 3L))
                .and(i -> i.ge(User::getAge, 20)));
        Assert.assertEquals(plainUsers3.size(), lambdaUsers3.size());
        print(plainUsers3);

        System.out.println("----- 自定义(sql注入) ------");
        List plainUsers4 = userMapper.selectList(new QueryWrapper()
                .apply("role_id = 2"));
        print(plainUsers4);

        UpdateWrapper uw = new UpdateWrapper<>();
        uw.set("email", null);
        uw.eq("id",4);
        userMapper.update(new User(), uw);
        User u4 = userMapper.selectById(4);
        Assert.assertNull(u4.getEmail());
    }

5.通用枚举

两种定义方法,接口继承和注解

public enum AgeEnum implements IEnum {
  ONE(1, "一岁"),
  TWO(2, "二岁"),
  THREE(3, "三岁");

  private int value;
  private String desc;

  AgeEnum(final int value, final String desc) {
    this.value = value;
    this.desc = desc;
  }

  @Override
  public Integer getValue() {
    return value;
  }
}

public enum GradeEnum {

    PRIMARY(1, "小学"),
    SECONDORY(2, "中学"),
    HIGH(3, "高中");

    GradeEnum(int code, String descp) {
        this.code = code;
        this.descp = descp;
    }

    @EnumValue
    private final int code;
    private final String descp;

    public int getCode() {
        return code;
    }

    public String getDescp() {
        return descp;
    }
}

测试

    @Test
    public void insert() {
        User user = new User();
        user.setName("K神");
        user.setAge(AgeEnum.ONE);
        user.setGrade(GradeEnum.HIGH);
        user.setGender(GenderEnum.MALE);
        user.setEmail("[email protected]");
        Assert.assertTrue(mapper.insert(user) > 0);
        // 成功直接拿会写的 ID
        System.err.println("\n插入成功 ID 为:" + user.getId());

        List list = mapper.selectList(null);
        for(User u:list){
            System.out.println(u);
            Assert.assertNotNull("age should not be null",u.getAge());
            if(u.getId().equals(user.getId())){
                Assert.assertNotNull("gender should not be null", u.getGender());
                Assert.assertNotNull("grade should not be null",u.getGrade());

            }
        }
    }

6.逻辑删除

首先要配置一个sql注入器(sqlInjector),然后使用TableLogic注解标记逻辑删除字段,其他使用方式不变

@Configuration
public class PlusConfiguration {

    @Bean
    public ISqlInjector sqlInjector() {
        return new LogicSqlInjector();
    }
}

@Data
public class User {
    private Integer id;
    private String name;
    private Integer age;
    private String email;
    @TableLogic
    private Integer isDelete;
}

测试代码

    @Test
    public void testLogicDeleteById() {
        userMapper.deleteById(1);
    }

输出日志

c.b.m.s.logic.mapper.UserMapper.delete   : ==>  Preparing: UPDATE user SET is_delete=1 WHERE is_delete=0 AND age = ? 
c.b.m.s.logic.mapper.UserMapper.delete   : ==> Parameters: 2(Integer)
c.b.m.s.logic.mapper.UserMapper.delete   : <==    Updates: 0

7.自动填充功能

在插入和更新表的时候自动填充设定的值

public class User {
    
    private Long id;
    
    private String name;
    
    private Integer age;
    
    private String email;
    
    @TableField(fill = FieldFill.INSERT_UPDATE)
    private String operator;
}

public class MyMetaObjectHandler implements MetaObjectHandler {

    private static final Logger LOGGER = LoggerFactory.getLogger(MyMetaObjectHandler.class);

    @Override
    public void insertFill(MetaObject metaObject) {
        LOGGER.info("start insert fill ....");
        //避免使用metaObject.setValue()
        this.setFieldValByName("operator", "Jerry", metaObject);
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        LOGGER.info("start update fill ....");
        this.setFieldValByName("operator", "Tom", metaObject);
    }
}

你可能感兴趣的:(mybatis plus学习笔记(1))