1.介紹
可以從官網(wǎng)看到介紹
https://mybatis.plus/guide/#%E7%89%B9%E6%80%A7
下面我們先無腦使用其功能被芳,不考慮其是如何實(shí)現(xiàn)的,例子都是官方的
2.第一個(gè)例子
由于例子采用了spring boot start以及數(shù)據(jù)采用了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.定義了一個(gè)User實(shí)體類
2.定義一個(gè)繼承自BaseMapper 的UserMapper映射類
3.調(diào)用UserMapper相關(guān)查詢方法
就是這么簡(jiǎn)單,有點(diǎn)類似JPA的感覺
3.CRUD
只需要調(diào)用BaseMapper相關(guān)方法即可
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);
// 成功直接拿會(huì)寫的 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.條件構(gòu)造器
即構(gòu)造一個(gè)QueryWrapper對(duì)象,直接一點(diǎn)可以理解為拼接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, "小學(xué)"),
SECONDORY(2, "中學(xué)"),
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;
}
}
測(cè)試
@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);
// 成功直接拿會(huì)寫的 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.邏輯刪除
首先要配置一個(gè)sql注入器(sqlInjector),然后使用TableLogic注解標(biāo)記邏輯刪除字段,其他使用方式不變
@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;
}
測(cè)試代碼
@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.自動(dòng)填充功能
在插入和更新表的時(shí)候自動(dòng)填充設(shè)定的值
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);
}
}