mybatis plus 实现关联查询
时间: 2023-11-24 19:53:26 浏览: 86
MyBatis-Plus多表联合查询并且分页(3表联合)
5星 · 资源好评率100%
MyBatis-Plus-Join可以帮助我们轻松实现关联查询,具体步骤如下:
1.定义实体类之间的关系,例如:
```java
public class User {
private Long id;
private String name;
private Integer age;
// 省略getter和setter方法
}
public class Order {
private Long id;
private Long userId;
private BigDecimal amount;
// 省略getter和setter方法
}
```
2.使用注解或XML配置关联查询,例如:
```java
@TableName("user")
public class User {
@TableId
private Long id;
private String name;
private Integer age;
@TableField(exist = false)
private List<Order> orders;
// 省略getter和setter方法
}
@TableName("order")
public class Order {
@TableId
private Long id;
private Long userId;
private BigDecimal amount;
// 省略getter和setter方法
}
```
```xml
<!-- userMapper.xml -->
<select id="getUserWithOrders" resultMap="userMap">
SELECT u.*, o.id AS order_id, o.amount
FROM user u
LEFT JOIN order o ON u.id = o.user_id
WHERE u.id = #{id}
</select>
<resultMap id="userMap" type="com.example.User">
<id column="id" property="id"/>
<result column="name" property="name"/>
<result column="age" property="age"/>
<collection property="orders" ofType="com.example.Order">
<id column="order_id" property="id"/>
<result column="amount" property="amount"/>
</collection>
</resultMap>
```
3.调用关联查询方法,例如:
```java
User user = userMapper.getUserWithOrders(1L);
List<Order> orders = user.getOrders();
```
阅读全文