这个在开发的过程中,难道不封装为vo吗
时间: 2024-04-17 18:24:57 浏览: 15
是的,在开发过程中,通常会封装一个VO(View Object)来表示关联查询的结果。VO是一个用于展示数据的对象,它可以包含多个实体类的属性,以满足前端或其他业务需求。
以下是一个示例的关联查询的VO封装:
```java
public class UserWithRoleVO {
private Long id;
private String name;
private Integer age;
private String roleName;
// 省略getter和setter方法
}
```
在Mapper接口中,查询方法的返回类型改为VO:
```java
public interface UserMapper extends BaseMapper<User> {
@Select("SELECT u.id, u.name, u.age, r.name AS roleName FROM user u LEFT JOIN role r ON u.role_id = r.id WHERE u.id = #{id}")
UserWithRoleVO selectUserWithRole(Long id);
}
```
在Service层和Controller层中,调用的返回类型也改为VO:
```java
@Service
public class UserServiceImpl implements UserService {
@Autowired
private UserMapper userMapper;
@Override
public UserWithRoleVO getUserWithRole(Long id) {
return userMapper.selectUserWithRole(id);
}
}
@RestController
@RequestMapping("/user")
public class UserController {
@Autowired
private UserService userService;
@GetMapping("/{id}")
public UserWithRoleVO getUserWithRole(@PathVariable Long id) {
return userService.getUserWithRole(id);
}
}
```
通过将关联查询结果封装为VO,可以更灵活地控制返回的数据结构,以满足业务需求。