mybatis plus学习笔记(1)
2019-03-31 本文已影响0人
兴浩
1.介绍
可以从官网看到介绍
https://mybatis.plus/guide/#%E7%89%B9%E6%80%A7
下面我们先无脑使用其功能,不考虑其是如何实现的,例子都是官方的
2.第一个例子
由于例子采用了spring boot start以及数据采用了h2,所以先略过此部分,直接使用,很无脑
代码示例1
@Data
public class User {
private Long id;
private String name;
private Integer age;
private String email;
}
public interface UserMapper extends BaseMapper<User> {
}
@RunWith(SpringRunner.class)
@SpringBootTest
public class SampleTest {
@Resource
private UserMapper userMapper;
@Test
public void testSelect() {
System.out.println(("----- selectAll method test ------"));
List<User> 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("abc@mp.com");
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<User>()
.lambda().eq(User::getName, "Sandy"))).isGreaterThan(0);
}
@Test
public void cUpdate() {
assertThat(mapper.updateById(new User().setId(1L).setEmail("ab@c.c"))).isGreaterThan(0);
assertThat(mapper.update(new User().setName("mp"),
Wrappers.<User>lambdaUpdate()
.set(User::getAge, 3)
.eq(User::getId, 2))).isGreaterThan(0);
}
@Test
public void dSelect() {
assertThat(mapper.selectById(1L).getEmail()).isEqualTo("ab@c.c");
User user = mapper.selectOne(new QueryWrapper<User>().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<User> plainUsers = userMapper.selectList(new QueryWrapper<User>().eq("role_id", 2L));
List<User> lambdaUsers = userMapper.selectList(new QueryWrapper<User>().lambda().eq(User::getRoleId, 2L));
Assert.assertEquals(plainUsers.size(), lambdaUsers.size());
print(plainUsers);
System.out.println("----- 带子查询(sql注入) ------");
List<User> plainUsers2 = userMapper.selectList(new QueryWrapper<User>()
.inSql("role_id", "select id from role where id = 2"));
List<User> lambdaUsers2 = userMapper.selectList(new QueryWrapper<User>().lambda()
.inSql(User::getRoleId, "select id from role where id = 2"));
Assert.assertEquals(plainUsers2.size(), lambdaUsers2.size());
print(plainUsers2);
System.out.println("----- 带嵌套查询 ------");
List<User> plainUsers3 = userMapper.selectList(new QueryWrapper<User>()
.nested(i -> i.eq("role_id", 2L).or().eq("role_id", 3L))
.and(i -> i.ge("age", 20)));
List<User> lambdaUsers3 = userMapper.selectList(new QueryWrapper<User>().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<User> plainUsers4 = userMapper.selectList(new QueryWrapper<User>()
.apply("role_id = 2"));
print(plainUsers4);
UpdateWrapper<User> 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<Integer> {
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("abc@mp.com");
Assert.assertTrue(mapper.insert(user) > 0);
// 成功直接拿会写的 ID
System.err.println("\n插入成功 ID 为:" + user.getId());
List<User> 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);
}
}