SpringBoot整合系列--整合MyBatis-plus

SpringBoot整合MyBatis-plus

步骤

第一步:添加必要的依赖

第一种是在已存在MyBatis的情况下,直接添加mybatis-plus包即可。


    com.baomidou
    mybatis-plus
    2.1.8

第二种是直接添加mybatis-plus的starter,它会自动导入mybatis的依赖包及其他相关依赖包


    com.baomidou
    mybatis-plus-boot-starter
    3.0.1

第二步:添加必要的配置

注意:Mybatis-plus是MyBatis的再封装,添加MyBatis-plus之后我们的设置针对的应该是MyBatis-plus,而不是MyBatis。

mybatis-plus:
  mapper-locations: classpath*:/mapper/*.xml
  type-aliases-package: com.example.springbootdemo.entity
  type-aliases-super-type: java.lang.Object
  type-handlers-package: com.example.springbootdemo.typeHandler
  type-enums-package: com.example.springbootdemo.enums

第三步:添加必要的配置类

@EnableTransactionManagement
@Configuration
@MapperScan("com.example.springbootdemo.plusmapper")
public class MyBatisPlusConfig {
    
    // mybatis-plus分页插件
    @Bean
    public PaginationInterceptor paginationInterceptor() {
        return new PaginationInterceptor();
    }
    
}

第四步:定义实体

@Data
@Builder
@ToString
@EqualsAndHashCode
@NoArgsConstructor
@AllArgsConstructor
@TableName(value = "ANIMAL")
public class Animal {
    @TableId(value = "ID",type = IdType.AUTO)
    private Integer id;
    @TableField(value = "NAME",exist = true)
    private String name;
    @TableField(value = "TYPE",exist = true)
    private AnimalType type;
    @TableField(value = "SEX",exist = true)
    private AnimalSex sex;
    @TableField(value = "MASTER",exist = true)
    private String master;
}
public enum AnimalType implements IEnum {
    CAT("1","猫"),DOG("2","狗"),TIGER("3","虎"),MOUSE("4","鼠"),MONKEY("5","猴"),LOAN("6","狮"),OTHER("7","其他");
    private final String value;
    private final String desc;
    AnimalType(final String value,final String desc){
        this.value=value;
        this.desc = desc;
    }
    @Override
    public Serializable getValue() {
        return value;
    }
    public String getDesc() {
        return desc;
    }
}
public enum AnimalSex implements IEnum {
    MALE("1","公"),FEMALE("2","母");
    private final String value;
    private final String desc;
    AnimalSex(final String value,final String desc){
        this.value = value;
        this.desc = desc;
    }
    @Override
    public Serializable getValue() {
        return value;
    }
    public String getDesc() {
        return desc;
    }
}

第五步:定义mapper接口

public interface AnimalRepository extends BaseMapper {
}

解说:使用MyBatis Plus后Mapper只要继承BaseMapper接口即可,即使不添加XML映射文件也可以实现该接口提供的增删改查功能,还可以配合Wrapper进行条件操作,当然这些操作都仅仅限于单表操作,一旦涉及多表联查,那么还是乖乖添加**Mapper.xml来自定义SQL吧!!!

第六步:定义service(重点)

@Service
@Log4j2
public class AnimalService {

    @Autowired
    private AnimalRepository animalRepository;

    //增
    public ResponseEntity addAnimal(final Animal animal) {
        animalRepository.insert(animal);
        return ResponseEntity.ok(animal);
    }

    //删
    public ResponseEntity deleteAnimalById(final int id){
        return ResponseEntity.ok(animalRepository.deleteById(id));
    }

    public ResponseEntity deleteAnimals(final Animal animal){
        return ResponseEntity.ok(animalRepository.delete(packWrapper(animal, WrapperType.QUERY)));
    }

    public ResponseEntity deleteAnimalsByIds(List ids){
        return ResponseEntity.ok(animalRepository.deleteBatchIds(ids));
    }

    public ResponseEntity deleteAnimalsByMap(final Animal animal){
        Map params = new HashMap<>();
        if(Objects.nonNull(animal.getId())){
            params.put("ID",animal.getId());
        }
        if(StringUtils.isNotEmpty(animal.getName())){
            params.put("NAME", animal.getName());
        }
        if(Objects.nonNull(animal.getType())){
            params.put("TYPE", animal.getType());
        }
        if(Objects.nonNull(animal.getSex())){
            params.put("SEX", animal.getSex());
        }
        if (StringUtils.isNotEmpty(animal.getMaster())){
            params.put("MASTER", animal.getMaster());
        }
        return ResponseEntity.ok(animalRepository.deleteByMap(params));
    }

    //改
    public ResponseEntity updateAnimals(final Animal animal, final Animal condition){
        return ResponseEntity.ok(animalRepository.update(animal, packWrapper(condition, WrapperType.UPDATE)));
    }

    public ResponseEntity updateAnimal(final Animal animal){
        Wrapper animalWrapper = new UpdateWrapper<>();
        ((UpdateWrapper) animalWrapper).eq("id",animal.getId());
        return ResponseEntity.ok(animalRepository.update(animal, animalWrapper));
    }

    //查
    public ResponseEntity getAnimalById(final int id){
        return ResponseEntity.ok(animalRepository.selectById(id));
    }

    public ResponseEntity getOneAnimal(final Animal animal){
        return ResponseEntity.ok(animalRepository.selectOne(packWrapper(animal, WrapperType.QUERY)));
    }

    public ResponseEntity> getAnimals(final Animal animal){
        return ResponseEntity.ok(animalRepository.selectList(packWrapper(animal, WrapperType.QUERY)));
    }

    public ResponseEntity> getAnimalsByIds(List ids){
        return ResponseEntity.ok(animalRepository.selectBatchIds(ids));
    }

    public ResponseEntity> getAnimalsByMap(final Animal animal){
        Map params = new HashMap<>();
        if(Objects.nonNull(animal.getId())){
            params.put("ID",animal.getId());
        }
        if(StringUtils.isNotEmpty(animal.getName())){
            params.put("NAME", animal.getName());
        }
        if(Objects.nonNull(animal.getType())){
            params.put("TYPE", animal.getType());
        }
        if(Objects.nonNull(animal.getSex())){
            params.put("SEX", animal.getSex());
        }
        if (StringUtils.isNotEmpty(animal.getMaster())){
            params.put("MASTER", animal.getMaster());
        }
        return ResponseEntity.ok(animalRepository.selectByMap(params));
    }

    public ResponseEntity>> getAnimalMaps(final Animal animal){
        return ResponseEntity.ok(animalRepository.selectMaps(packWrapper(animal, WrapperType.QUERY)));
    }

    //查个数
    public ResponseEntity getCount(final Animal animal){
        return ResponseEntity.ok(animalRepository.selectCount(packWrapper(animal, WrapperType.QUERY)));
    }

    //分页查询
    public ResponseEntity> getAnimalPage(final Animal animal,final int pageId,final int pageSize){
        Page page = new Page<>();
        page.setCurrent(pageId);
        page.setSize(pageSize);
        return ResponseEntity.ok((Page) animalRepository.selectPage(page,packWrapper(animal, WrapperType.QUERY)));
    }

    private Wrapper packWrapper(final Animal animal, WrapperType wrapperType){
        switch (wrapperType){
            case QUERY:
                QueryWrapper wrapper = new QueryWrapper<>();
                if (Objects.nonNull(animal.getId()))
                    wrapper.eq("ID", animal.getId());
                if (StringUtils.isNotEmpty(animal.getName()))
                    wrapper.eq("name", animal.getName());
                if (Objects.nonNull(animal.getType()))
                    wrapper.eq("type", animal.getType());
                if (Objects.nonNull(animal.getSex()))
                    wrapper.eq("sex", animal.getSex());
                if (StringUtils.isNotEmpty(animal.getMaster()))
                    wrapper.eq("master", animal.getMaster());
                return wrapper;
            case UPDATE:
                UpdateWrapper wrapper2 = new UpdateWrapper<>();
                if (Objects.nonNull(animal.getId()))
                    wrapper2.eq("ID", animal.getId());
                if (StringUtils.isNotEmpty(animal.getName()))
                    wrapper2.eq("name", animal.getName());
                if (Objects.nonNull(animal.getType()))
                    wrapper2.eq("type", animal.getType());
                if (Objects.nonNull(animal.getSex()))
                    wrapper2.eq("sex", animal.getSex());
                if (StringUtils.isNotEmpty(animal.getMaster()))
                    wrapper2.eq("master", animal.getMaster());
                return wrapper2;
            case QUERYLAMBDA:
                LambdaQueryWrapper wrapper3 = new QueryWrapper().lambda();
                if (Objects.nonNull(animal.getId()))
                    wrapper3.eq(Animal::getId, animal.getId());
                if (StringUtils.isNotEmpty(animal.getName()))
                    wrapper3.eq(Animal::getName, animal.getName());
                if (Objects.nonNull(animal.getType()))
                    wrapper3.eq(Animal::getType, animal.getType());
                if (Objects.nonNull(animal.getSex()))
                    wrapper3.eq(Animal::getSex, animal.getSex());
                if (StringUtils.isNotEmpty(animal.getMaster()))
                    wrapper3.eq(Animal::getMaster, animal.getMaster());
                return wrapper3;
            case UPDATELAMBDA:
                LambdaUpdateWrapper wrapper4 = new UpdateWrapper().lambda();
                if (Objects.nonNull(animal.getId()))
                    wrapper4.eq(Animal::getId, animal.getId());
                if (StringUtils.isNotEmpty(animal.getName()))
                    wrapper4.eq(Animal::getName, animal.getName());
                if (Objects.nonNull(animal.getType()))
                    wrapper4.eq(Animal::getType, animal.getType());
                if (Objects.nonNull(animal.getSex()))
                    wrapper4.eq(Animal::getSex, animal.getSex());
                if (StringUtils.isNotEmpty(animal.getMaster()))
                    wrapper4.eq(Animal::getMaster, animal.getMaster());
                return wrapper4;
            default:return null;
        }
    }
}
enum WrapperType{
    UPDATE,UPDATELAMBDA,QUERY,QUERYLAMBDA;
}

第七步:定义controller

@RestController
@RequestMapping("animal")
@Api(description = "动物接口")
@Log4j2
public class AnimalApi {
    @Autowired
    private AnimalService animalService;
    @RequestMapping(value = "addAnimal",method = RequestMethod.PUT)
    @ApiOperation(value = "添加动物",notes = "添加动物",httpMethod = "PUT")
    public ResponseEntity addAnimal(final Animal animal){
        return animalService.addAnimal(animal);
    }
    @RequestMapping(value = "deleteAnimalById", method = RequestMethod.DELETE)
    @ApiOperation(value = "删除一个动物",notes = "根据ID删除动物",httpMethod = "DELETE")
    public ResponseEntity deleteAnimalById(final int id){
        return animalService.deleteAnimalById(id);
    }
    @RequestMapping(value = "deleteAnimalsByIds",method = RequestMethod.DELETE)
    @ApiOperation(value = "删除多个动物",notes = "根据Id删除多个动物",httpMethod = "DELETE")
    public ResponseEntity deleteAnimalsByIds(Integer[] ids){
        return animalService.deleteAnimalsByIds(Arrays.asList(ids));
    }
    @RequestMapping(value = "deleteAnimals", method = RequestMethod.DELETE)
    @ApiOperation(value = "删除动物",notes = "根据条件删除动物",httpMethod = "DELETE")
    public ResponseEntity deleteAnimalsByMaps(final Animal animal){
        return animalService.deleteAnimalsByMap(animal);
    }
    @RequestMapping(value = "deleteAnimals2", method = RequestMethod.DELETE)
    @ApiOperation(value = "删除动物",notes = "根据条件删除动物",httpMethod = "DELETE")
    public ResponseEntity deleteAnimals(final Animal animal){
        return animalService.deleteAnimals(animal);
    }
    @RequestMapping(value = "getAnimalById",method = RequestMethod.GET)
    @ApiOperation(value = "获取一个动物",notes = "根据ID获取一个动物",httpMethod = "GET")
    public ResponseEntity getAnimalById(final int id){
        return animalService.getAnimalById(id);
    }
    // 注意,这里参数animal不能用RequstBody标注,否则接收不到参数
    // @RequestBody只能用在只有一个参数模型的方法中,用于将所有请求体中携带的参数全部映射到这个请求参数模型中
    @RequestMapping(value = "getAnimalsByPage")
    @ApiOperation(value = "分页获取动物们",notes = "分页获取所有动物", httpMethod = "GET")
    public ResponseEntity> getAnimalsByPage(@RequestParam final int pageId, @RequestParam final int pageSize, final Animal animal) {
        return animalService.getAnimalPage(animal==null?Animal.builder().build():animal, pageId, pageSize);
    }
    @RequestMapping(value = "updateAnimal")
    @ApiOperation(value = "更新动物", notes = "根据条件更新",httpMethod = "POST")
    public ResponseEntity updateAnimals(final Animal animal){
        return animalService.updateAnimal(animal);
    }
}

你可能感兴趣的:(编程)