mybatisplus多表关联+分页
时间: 2023-11-24 16:52:36 浏览: 97
以下是使用MyBatis Plus实现多表关联和分页查询的示例代码:
1. 首先,在实体类中定义需要关联的字段,并使用@TableField注解指定关联的表和字段名:
```java
public class Order {
private Long id;
private Long userId;
private String orderNo;
@TableField(exist = false)
private User user; // 省略getter和setter方法
}
```
2. 在Mapper接口中定义关联查询的方法,使用@Select注解指定SQL语句:
```java
public interface OrderMapper extends BaseMapper<Order> {
@Select("SELECT o.*, u.username FROM `order` o LEFT JOIN user u ON o.user_id = u.id WHERE o.id = #{id}")
Order selectOrderWithUserById(@Param("id") Long id);
}
```
3. 在Service中调用Mapper接口的方法进行查询,并使用PageHelper进行分页:
```java
@Service
public class OrderServiceImpl implements OrderService {
@Autowired
private OrderMapper orderMapper;
@Override
public PageInfo<Order> selectOrderWithUserByPage(int pageNum, int pageSize) {
PageHelper.startPage(pageNum, pageSize);
List<Order> orderList = orderMapper.selectOrderWithUser();
return new PageInfo<>(orderList);
}
}
```
4. 最后,在Controller中调用Service的方法获取分页数据:
```java
@RestController
@RequestMapping("/order")
public class OrderController {
@Autowired
private OrderService orderService;
@GetMapping("/list")
public PageInfo<Order> getOrderList(@RequestParam(defaultValue = "1") int pageNum,
@RequestParam(defaultValue = "10") int pageSize) {
return orderService.selectOrderWithUserByPage(pageNum, pageSize);
}
}
```
阅读全文