mybatisplus自定义slq查询分页
时间: 2023-09-07 10:04:19 浏览: 142
MyBatis-Plus是一个基于MyBatis的插件,提供了许多便捷的功能,包括自定义SQL查询和分页功能。
要自定义SQL查询并进行分页,需要按照以下步骤进行:
1. 首先,在你的实体类上使用`@TableName`注解指定数据库表名。这是MyBatis-Plus的要求。
2. 在你的Mapper接口中创建自定义的SQL查询方法。例如,你可以创建一个方法叫做`selectCustomPage`,其中的SQL语句是你自己编写的。
```
public interface UserMapper extends BaseMapper<User> {
@Select("SELECT * FROM user WHERE age > #{age}")
IPage<User> selectCustomPage(Page<User> page, int age);
}
```
3. 在你的Service中调用Mapper中的自定义查询方法,并传入分页参数。
```
@Service
public class UserServiceImpl implements UserService {
@Autowired
private UserMapper userMapper;
@Override
public IPage<User> getCustomPage(int pageNum, int pageSize, int age) {
Page<User> page = new Page<>(pageNum, pageSize);
IPage<User> userPage = userMapper.selectCustomPage(page, age);
return userPage;
}
}
```
4. 在你的Controller中调用Service中的方法,并将返回的分页对象转换成你想要的格式。
```
@RestController
@RequestMapping("/users")
public class UserController {
@Autowired
private UserService userService;
@GetMapping
public ResultData getUsers(@RequestParam(defaultValue = "1") int pageNum,
@RequestParam(defaultValue = "10") int pageSize,
@RequestParam int age) {
IPage<User> userPage = userService.getCustomPage(pageNum, pageSize, age);
List<User> userList = userPage.getRecords();
long total = userPage.getTotal();
return new ResultData(userList, total);
}
}
```
通过以上步骤,你就可以自定义SQL查询并进行分页了。注意,在自定义的SQL语句中,可以使用MyBatis的占位符`#{}`来接收参数。
阅读全文
相关推荐












