@MapperScan("com.cgdcge.cc.mapper") @SpringBootApplication public class Main { public static void main(String[] args) {SpringApplication.run(Main.class,args); } @Bean public MybatisPlusInterceptor mybatisPlusInterceptor() { MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor(); interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL)); return interceptor; }
}
实体类
1 2 3 4 5 6 7
@Data public class User { private Long id; private String name; private Integer age; private String email; }
UserMapper 接口
1 2 3
public interface UserMapper extends BaseMapper<User> {
}
测试类
1 2 3 4 5 6 7 8 9 10 11
@SpringBootTest public class Springtext { @Autowired private UserMapper userMapper;
@MapperScan("com.cgdcge.cc.mapper") @SpringBootApplication public class Main { public static void main(String[] args) {SpringApplication.run(Main.class,args); } @Bean public MybatisPlusInterceptor mybatisPlusInterceptor() { MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor(); interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL)); return interceptor; }
@Test publicvoidtest01(){ //查询用户名包含a,年龄在20到30之间,并且邮箱不为null的用户信息 //SELECT id,username AS name,age,email,is_deleted FROM t_user WHERE is_deleted=0 AND (username LIKE ? AND age BETWEEN ? AND ? AND email IS NOT NULL) QueryWrapper<User> queryWrapper = newQueryWrapper<>(); queryWrapper.like("username", "a") .between("age", 20, 30) .isNotNull("email"); List<User> list = userMapper.selectList(queryWrapper); list.forEach(System.out::println);
组装排序条件:
1 2 3 4 5 6 7 8 9 10 11
@Test publicvoidtest02(){ //按年龄降序查询用户,如果年龄相同则按id升序排列 //SELECT id,username AS name,age,email,is_deleted FROM t_user WHERE is_deleted=0 ORDER BY age DESC,id ASC QueryWrapper<User> queryWrapper = newQueryWrapper<>(); queryWrapper .orderByDesc("age") .orderByAsc("id"); List<User> users = userMapper.selectList(queryWrapper); users.forEach(System.out::println); }
组装删除条件:
1 2 3 4 5 6 7 8 9 10
@Test publicvoidtest03(){ //删除email为空的用户 //DELETE FROM t_user WHERE (email IS NULL) QueryWrapper<User> queryWrapper = newQueryWrapper<>(); queryWrapper.isNull("email"); //条件构造器也可以构建删除语句的条件 intresult= userMapper.delete(queryWrapper); System.out.println("受影响的行数:" + result); }
and 和 or 关键字使用(修改):
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
@Test publicvoidtest04() { QueryWrapper<User> queryWrapper = newQueryWrapper<>(); //将年龄大于20并且用户名中包含有a或邮箱为null的用户信息修改 //UPDATE t_user SET age=?, email=? WHERE username LIKE ? AND age > ? OR email IS NULL) queryWrapper .like("username", "a") .gt("age", 20) .or() .isNull("email"); Useruser=newUser(); user.setAge(18); user.setEmail("user@atguigu.com"); intresult= userMapper.update(user, queryWrapper); System.out.println("受影响的行数:" + result); }