mybait-plus 连表查询
时间: 2023-07-18 08:24:20 浏览: 67
支持连表查询的mybatis-plus
5星 · 资源好评率100%
MyBatis-Plus 提供了多种方式来进行连表查询,以下是其中几种常用的方式:
1. 使用 `@TableName` 注解来定义表名,再使用 `@TableField` 注解来定义字段名,然后使用 MyBatis-Plus 提供的 `Wrapper` 类进行连表查询,例如:
```java
@TableName("user")
public class User {
@TableField("id")
private Long id;
@TableField("name")
private String name;
@TableField("age")
private Integer age;
// ...
}
@TableName("order")
public class Order {
@TableField("id")
private Long id;
@TableField("user_id")
private Long userId;
@TableField("order_no")
private String orderNo;
// ...
}
public interface UserMapper extends BaseMapper<User> {
@Select("select u.*, o.* from user u left join order o on u.id = o.user_id")
List<Map<String, Object>> selectUserAndOrder();
}
```
2. 使用 `@TableId` 注解来定义主键,然后使用 MyBatis-Plus 提供的 `@JoinQuery` 注解进行连表查询,例如:
```java
@TableId("id")
public class User {
private Long id;
private String name;
private Integer age;
// ...
}
@TableId("id")
public class Order {
private Long id;
private Long userId;
private String orderNo;
// ...
}
public interface UserMapper extends BaseMapper<User> {
@JoinQuery(tableAlias = "u", joinTableAlias = "o", joinFieldName = "user_id", joinTable = "order", selectFields = "order_no")
List<User> selectUserAndOrder();
}
```
3. 使用 MyBatis-Plus 提供的 `QueryWrapper` 类进行连表查询,例如:
```java
public interface UserMapper extends BaseMapper<User> {
@Select("select u.*, o.* from user u left join order o on u.id = o.user_id")
List<Map<String, Object>> selectUserAndOrder(QueryWrapper<User> wrapper);
}
```
阅读全文