springboot之mybatis完美一击mybatis-plus
说明
上一篇讲解了关于mybatis实际开发中常用的一些技巧,但写了太多sql,有么有其他方式简化我们写的sql,少写?答案是肯定的
添加依赖
#只需要在之前mybatis基础上mybatis-spring-boot-starter换成mybatis-plus-boot-starte
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
</dependency>
entity
entity:
@Data
@TableName(value = "tb_employee")//指定表名
public class Employee {
//value与数据库主键列名一致,若实体类属性名与表主键列名一致可省略value
@TableId(value = "id",type = IdType.AUTO)//指定自增策略
private Integer id;
//若没有开启驼峰命名,或者表中列名不符合驼峰规则,可通过该注解指定数据库表中的列名,exist标明数据表中有没有对应列
@TableField(value = "last_name",exist = true)
private String lastName;
private String email;
private Integer gender;
private Integer age;
}
mapper
public interface EmplopyeeDao extends BaseMapper<Employee> {
}
分页插件
@Configuration
@MapperScan("com.neo.mapper")
public class MybatisPlusConfig {
/**
* 分页插件
*/
@Bean
public PaginationInterceptor paginationInterceptor() {
return new PaginationInterceptor();
}
}
mp的通用crud
@RunWith(SpringRunner.class)
@SpringBootTest
public class MyBatisPlusTest {
@Autowired
private UserMapper userMapper;
@Test
public void testSelectOne() {
User user = userMapper.selectById(1L);
System.out.println(user);
}
@Test
public void testInsert() {
User user = new User();
user.setName("微笑");
user.setAge(3);
user.setEmail("neo@tooool.org");
assertThat(userMapper.insert(user)).isGreaterThan(0);
// 成功直接拿会写的 ID
assertThat(user.getId()).isNotNull();
}
@Test
public void testDelete() {
assertThat(userMapper.deleteById(3L)).isGreaterThan(0);
assertThat(userMapper.delete(new QueryWrapper<User>()
.lambda().eq(User::getName, "smile"))).isGreaterThan(0);
}
@Test
public void testUpdate() {
User user = userMapper.selectById(2);
assertThat(user.getAge()).isEqualTo(36);
assertThat(user.getName()).isEqualTo("keep");
userMapper.update(
null,
Wrappers.<User>lambdaUpdate().set(User::getEmail, "123@123").eq(User::getId, 2)
);
assertThat(userMapper.selectById(2).getEmail()).isEqualTo("123@123");
}
@Test
public void testSelect() {
List<User> userList = userMapper.selectList(null);
Assert.assertEquals(5, userList.size());
userList.forEach(System.out::println);
}
@Test
public void testSelectCondition() {
QueryWrapper<User> wrapper = new QueryWrapper<>();
wrapper.select("max(id) as id");
List<User> userList = userMapper.selectList(wrapper);
userList.forEach(System.out::println);
}
@Test
public void testPage() {
System.out.println("----- baseMapper 自带分页 ------");
Page<User> page = new Page<>(1, 2);
IPage<User> userIPage = userMapper.selectPage(page, new QueryWrapper<User>()
.gt("age", 6));
assertThat(page).isSameAs(userIPage);
System.out.println("总条数 ------> " + userIPage.getTotal());
System.out.println("当前页数 ------> " + userIPage.getCurrent());
System.out.println("当前每页显示数 ------> " + userIPage.getSize());
print(userIPage.getRecords());
System.out.println("----- baseMapper 自带分页 ------");
}
private <T> void print(List<T> list) {
if (!CollectionUtils.isEmpty(list)) {
list.forEach(System.out::println);
}
}
}
以上基本的 CRUD 操作,我们仅仅需要继承一个 BaseMapper 即可实现大部分单表 CRUD
操作。BaseMapper 提供了多达 17 个方法供使用, 可以极其方便的实现单一、批量、
分页等操作,极大的减少开发负担。
一些细节
两个update操作的区别
注:注意这两个update操作的区别,updateById方法,没有传值的字段不会进行更新,比如只传入了lastName,那么age、gender等属性就会保留原来的值;updateAllColumnById方法,顾名思义,会更新所有的列,没有传值的列会更新为null。
查询
selectOne这个方法的sql语句就是where id = 1 and last_name = 更新测试,若是符合这个条件的记录不止一条,那么就会报错。
这时也可以
根据查询条件返回多条数据:
当符合指定条件的记录数有多条时,上面那个方法就会报错,就应该用这个方法。
Map<String,Object> columnMap = new HashMap<>();
columnMap.put("last_name","东方不败");//写表中的列名
columnMap.put("gender","1");
List<Employee> employees = emplopyeeDao.selectByMap(columnMap);
System.out.println(employees.size());
注:查询条件用map集合封装,columnMap,写的是数据表中的列名,而非实体类的属性名。比如属性名为lastName,数据表中字段为last_name,这里应该写的是last_name。selectByMap方法返回值用list集合接收。
通过id批量查询:
List<Integer> idList = new ArrayList<>();
idList.add(1);
idList.add(2);
idList.add(3);
List<Employee> employees = emplopyeeDao.selectBatchIds(idList);
System.out.println(employees);
注:把需要查询的id都add到list集合中,然后调用selectBatchIds方法,传入该list集合即可,该方法返回的是对应id的所有记录,所有返回值也是用list接收。
删除
delete操作:
(1)、根据id删除:
emplopyeeDao.deleteById(1);
(2)、根据条件删除:
Map<String,Object> columnMap = new HashMap<>();
columnMap.put("gender",0);
columnMap.put("age",18);
emplopyeeDao.deleteByMap(columnMap);
注:该方法与selectByMap类似,将条件封装在columnMap中,然后调用deleteByMap方法,传入columnMap即可,返回值是Integer类型,表示影响的行数。
(3)、根据id批量删除:
List<Integer> idList = new ArrayList<>();
idList.add(1);
idList.add(2);
emplopyeeDao.deleteBatchIds(idList);
注:该方法和selectBatchIds类似,把需要删除的记录的id装进idList,然后调用deleteBatchIds,传入idList即可。
条件构造器(EntityWrapper),和上面代码mp的通用crud的QueryWrapper功能一样
接下来就直接看几个案例体会EntityWrapper的使用。
1、分页查询年龄在18 - 50且gender为0、姓名为tom的用户:
List<Employee> employees = emplopyeeDao.selectPage(new Page<Employee>(1,3),
new EntityWrapper<Employee>()
.between("age",18,50)
.eq("gender",0)
.eq("last_name","tom")
);
注:由此案例可知,分页查询和之前一样,new 一个page对象传入分页信息即可。至于分页条件,new 一个EntityWrapper对象,调用该对象的相关方法即可。between方法三个参数,分别是column、value1、value2,该方法表示column的值要在value1和value2之间;eq是equals的简写,该方法两个参数,column和value,表示column的值和value要相等。注意column是数据表对应的字段,而非实体类属性字段。
2、查询gender为0且名字中带有老师、或者邮箱中带有a的用户:
List<Employee> employees = emplopyeeDao.selectList(
new EntityWrapper<Employee>()
.eq("gender",0)
.like("last_name","老师")
//.or()//和or new 区别不大
.orNew()
.like("email","a")
);
注:未说分页查询,所以用selectList即可,用EntityWrapper的like方法进行模糊查询,like方法就是指column的值包含value值,此处like方法就是查询last_name中包含“老师”字样的记录;“或者”用or或者orNew方法表示,这两个方法区别不大,用哪个都可以,可以通过控制台的sql语句自行感受其区别。
3、查询gender为0,根据age排序,简单分页:
List<Employee> employees = emplopyeeDao.selectList(
new EntityWrapper<Employee>()
.eq("gender",0)
.orderBy("age")//直接orderby 是升序,asc
.last("desc limit 1,3")//在sql语句后面追加last里面的内容(改为降序,同时分页)
);
注:简单分页是指不用page对象进行分页。orderBy方法就是根据传入的column进行升序排序,若要降序,可以使用orderByDesc方法,也可以如案例中所示用last方法;last方法就是将last方法里面的value值追加到sql语句的后面,在该案例中,最后的sql语句就变为select ······ order by desc limit 1, 3,追加了desc limit 1,3所以可以进行降序排序和分页。
4、分页查询年龄在18 - 50且gender为0、姓名为tom的用户:
条件构造器除了EntityWrapper,还有Condition。用Condition来处理一下这个需求:
List<Employee> employees = emplopyeeDao.selectPage(
new Page<Employee>(1,2),
Condition.create()
.between("age",18,50)
.eq("gender","0")
);
注:Condition和EntityWrapper的区别就是,创建条件构造器时,EntityWrapper是new出来的,而Condition是调create方法创建出来。
5、根据条件更新:
@Test
public void testEntityWrapperUpdate(){
Employee employee = new Employee();
employee.setLastName("苍老师");
employee.setEmail("cjk@sina.com");
employee.setGender(0);
emplopyeeDao.update(employee,
new EntityWrapper<Employee>()
.eq("last_name","tom")
.eq("age",25)
);
}
注:该案例表示把last_name为tom,age为25的所有用户的信息更新为employee中设置的信息。
6、根据条件删除:
emplopyeeDao.delete(
new EntityWrapper<Employee>()
.eq("last_name","tom")
.eq("age",16)
);
注:该案例表示把last_name为tom、age为16的所有用户删除。
简单介绍ActiveRecord
1、entity:
@Data
public class User extends Model<User> {
private Integer id;
private String name;
private Integer age;
private Integer gender;
//重写这个方法,return当前类的主键
@Override
protected Serializable pkVal() {
return id;
}
}
注:实体类继承Model类,重写pkVal方法。
2、mapper:
public interface UserDao extends BaseMapper<User> {
}
注:虽然AR模式用不到该接口,但是一定要定义,否则使用AR时会报空指针异常。
3、使用AR:
(1)、AR插入操作:
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration({"classpath:spring/spring-dao.xml"})
public class TestAR {
@Test
public void testArInsert(){
User user = new User();
user.setName("林青霞");
user.setAge(22);
user.setGender(1);
boolean result = user.insert();
System.out.println(result);
}
}