首先添加依赖:
<!--引入 mybatis-plus,有单独的分页插件-->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.4.2</version>
</dependency>
然后修改yml 配置,将之前的 mybatis 注释掉,添加新的 plus 插件
# mybatis-plus配置
mybatis-plus:
configuration:
log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
map-underscore-to-camel-case: true
typeAliasesPackage: com.xxxx.qcby.entity #对应实体类
mapperLocations: classpath:mapper/*.xml #xml 文件
然后可以开始使用了,比如写一个demo,先写 mapper 层
需要继承 BaseMapper 类,泛型是想传递的泛型,这里写的是 Role
package com.xxxx.qcby.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.xxxx.qcby.entity.Role;
/**
* @Classname DemoMapper
* @Description 测试
* @Date 2021/8/29 17:28
* @Created by thx
*/
public interface DemoMapper extends BaseMapper<Role> {
}
然后是 service 层的接口:
继承 IService 类,泛型保持一致
package com.xxxx.qcby.service;
import com.baomidou.mybatisplus.extension.service.IService;
import com.xxxx.qcby.entity.Role;
/**
* @Classname DemoService
* @Description 测试
* @Date 2021/8/29 17:28
* @Created by thx
*/
public interface DemoService extends IService<Role> {
}
实现类:
实现类,首先继承ServiceImpl 类,传递 Mapper 和 实体类对象,然后实现写的接口
package com.xxxx.qcby.service.impl;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xxxx.qcby.entity.Role;
import com.xxxx.qcby.mapper.DemoMapper;
import com.xxxx.qcby.service.DemoService;
import org.springframework.stereotype.Service;
/**
* @Classname DemoServiceImpl
* @Description 测试
* @Date 2021/8/29 17:29
* @Created by thx
*/
@Service
public class DemoServiceImpl extends ServiceImpl<DemoMapper, Role> implements DemoService {
}
此时就可以在 controller 里面写单表查询的方法了:
自带单表查询:
package com.xxxx.qcby.controller;
import com.xxxx.qcby.common.web.ResultJson;
import com.xxxx.qcby.entity.Role;
import com.xxxx.qcby.service.DemoService;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import javax.annotation.Resource;
import java.util.List;
/**
* @Classname DemoController
* @Description 测试
* @Date 2021/8/29 17:30
* @Created by thx
*/
@RestController
@RequestMapping("demo")
public class DemoController {
@Resource
private DemoService demoService;
@RequestMapping("listAll")
public ResultJson listAll() {//查询
return ResultJson.success(demoService.list());
}
@RequestMapping("save")
public ResultJson save(Role role) {//添加
return ResultJson.success(demoService.save(role));
}
@RequestMapping("deleteByIds")//多删
public ResultJson deleteByIds(@RequestParam List<Long> ids) {
return ResultJson.success(demoService.removeByIds(ids));
}
@RequestMapping("updateById")//修改
public ResultJson updateById(Role role) {
return ResultJson.success(demoService.updateById(role));
}
}