mybatisplus 一对多映射
时间: 2023-07-01 09:28:24 浏览: 90
Mybatis-plus 支持一对多的映射关系,可以通过以下步骤实现:
1. 定义需要查询的实体类和关联实体类,例如:
```java
@Data
public class User implements Serializable {
private static final long serialVersionUID = 1L;
private Long id;
private String name;
private Integer age;
private String email;
private List<Order> orders;
}
@Data
public class Order implements Serializable {
private static final long serialVersionUID = 1L;
private Long id;
private Long userId;
private String orderNo;
}
```
2. 编写 Mapper 接口,定义一对多查询的方法,例如:
```java
public interface UserMapper extends BaseMapper<User> {
@Select("SELECT * FROM order WHERE user_id = #{userId}")
List<Order> selectOrdersByUserId(Long userId);
}
```
3. 在 Service 层方法中,通过调用 Mapper 接口方法获取关联数据,并设置到主实体中,例如:
```java
@Service
public class UserServiceImpl implements UserService {
@Autowired
private UserMapper userMapper;
@Override
public List<User> selectUserWithOrders() {
List<User> users = userMapper.selectList(null);
users.forEach(user -> {
List<Order> orders = userMapper.selectOrdersByUserId(user.getId());
user.setOrders(orders);
});
return users;
}
}
```
4. 在 Controller 中调用 Service 层方法,例如:
```java
@RestController
@RequestMapping("/user")
public class UserController {
@Autowired
private UserService userService;
@GetMapping("/orders")
public Result<List<User>> selectUserWithOrders() {
return Result.success(userService.selectUserWithOrders());
}
}
```
注意:在使用一对多映射时,可以使用 @TableField 注解指定关联字段的映射关系,例如:
```java
@Data
public class User implements Serializable {
private static final long serialVersionUID = 1L;
private Long id;
private String name;
private Integer age;
private String email;
@TableField(exist = false) // 不是数据库表字段
private List<Order> orders;
}
@Data
public class Order implements Serializable {
private static final long serialVersionUID = 1L;
private Long id;
@TableField("user_id") // 指定关联字段映射
private Long userId;
private String orderNo;
}
```
阅读全文