@EnableTransactionManagement
@Configuration
@MapperScan("com.cy.springboot.mapper")
public class MybatisPlusConfig {
// 分页插件
@Bean
public MybatisPlusInterceptor mybatisPlusInterceptor() {
//构建拦截器对象
MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
// 添加分页拦截器,并指定数据库类型为MySQL
interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));
// 返回拦截器对象
return interceptor;
}
}
一、定义一个接口数据返回类
自定义异常值
Constants
public interface Constants {
String CODE_200 = "200"; //成功
String CODE_401 = "401"; //权限不足
String CODE_400 = "400"; //参数错误
String CODE_500 = "500"; //系统错误
String CODE_600 = "600"; //其他业务错误
}
接口数据返回类
Result.java
@Data //getter/setter
@AllArgsConstructor //无参构造
@NoArgsConstructor //有参构造
public class Result {
private String code;
private String msg;
private Object data;
public static Result success() {
return new Result(Constants.CODE_200, "", null);
}
public static Result success(Object data) {
return new Result(Constants.CODE_200, "", data);
}
public static Result error(String code, String msg) {
return new Result(code, msg, null);
}
public static Result error() {
return new Result(Constants.CODE_500, "系统错误", null);
}
}
二、编写控制层接口
UserController.java
方式一@RestController
@RequestMapping("/user")
public class UserController {
//分页查询
@GetMapping("/page")
public Result findPage() {
Page<User> userPage = new Page<>(); //Page需指定实体类对象
userPage.setCurrent(1); //设置当前页
userPage.setSize(1); //设置每页多少条数据
Page<User> page = userService.page(userPage); //调用userService.page()方法,传入userPage,返回Page对象
return Result.success(page);
}
接口测试
打印sql
@RestController
@RequestMapping("/user")
public class UserController {
//分页查询
@GetMapping("/page")
public Result findPage(@RequestParam Integer pageNum,
@RequestParam Integer pageSize) {
QueryWrapper<User> queryWrapper = new QueryWrapper<>(); //通过QueryWrapper构造器,指定构造对象
queryWrapper.orderByDesc("id");//使用wrapper的条件构造器
return Result.success(userService.page(new Page<>(pageNum, pageSize), queryWrapper));//wrapper可以丢到userService.page()方法中
}
}
接口测试,
http://localhost:8081/user/page?pageNum=1&pageSize=1
query中需要指定pageNum和pageSize(当前页,每页数据条数)
打印sql
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)