mybatis-plus多表分页查询 自定义返回对象
时间: 2023-09-23 11:04:42 浏览: 203
在 MyBatis-Plus 中,可以通过使用 @SqlResultSetMapping 注解和 @Query 注解来实现自定义返回对象的多表分页查询。
首先,需要使用 @SqlResultSetMapping 注解定义自定义返回对象。该注解的 name 属性指定了返回对象的名称,classes 属性指定了返回对象的属性。例如:
```java
@SqlResultSetMapping(name = "UserAndOrderMapping", classes = {
@ConstructorResult(targetClass = UserAndOrderDTO.class,
columns = {
@ColumnResult(name = "id", type = Long.class),
@ColumnResult(name = "name", type = String.class),
@ColumnResult(name = "order_id", type = Long.class),
@ColumnResult(name = "order_name", type = String.class)
})
})
public class UserAndOrderDTO {
private Long id;
private String name;
private Long orderId;
private String orderName;
public UserAndOrderDTO(Long id, String name, Long orderId, String orderName) {
this.id = id;
this.name = name;
this.orderId = orderId;
this.orderName = orderName;
}
// getters and setters
}
```
然后,在使用 @Query 注解时,需要指定 nativeQuery 属性为 true,表示使用原生 SQL 查询。同时,需要将 @SqlResultSetMapping 注解的 name 属性值作为 resultClass 属性的值传入 @Query 注解。例如:
```java
@Query(value = "SELECT u.id, u.name, o.id AS order_id, o.name AS order_name FROM user u LEFT JOIN order o ON u.id = o.user_id",
countQuery = "SELECT COUNT(*) FROM user u LEFT JOIN order o ON u.id = o.user_id",
nativeQuery = true, resultSetMapping = "UserAndOrderMapping")
Page<UserAndOrderDTO> selectUserAndOrderPage(Page page);
```
这样就可以实现自定义返回对象的多表分页查询了。
阅读全文