Spring Boot接口响应复合对象缺失及冗余字段问题求解
问题1:User对象userRoles集合为空修复方案
1. 修正关联注解配置
你当前User类中@OneToMany的mappedBy属性配置错误,mappedBy需要指向UserRoleMapping类中关联User的属性名,而不是主键id:
// 修改前 @OneToMany(mappedBy = "id", fetch = FetchType.EAGER, cascade = CascadeType.ALL) private Set<UserRoleMapping> userRoles; // 修改后 @OneToMany(mappedBy = "user", fetch = FetchType.EAGER, cascade = CascadeType.ALL) private Set<UserRoleMapping> userRoles;
2. 维护双向关联关系
JPA双向关联需要手动维护双方的关联状态,内存中的User对象不会自动同步新增的关联数据,两种处理方式:
- 方式一:新增/查询到关联数据后,手动更新User的userRoles集合:
if (urm.size() == 0) { userRoleMapping = new UserRoleMapping(Role.ROLE_CUSTOMER, user); userRoleMappingRepository.save(userRoleMapping); // 手动添加到User的关联集合 user.getUserRoles().add(userRoleMapping); } else { userRoleMapping = urm.get(0); // 把查询到的所有关联数据同步到User对象 user.setUserRoles(new HashSet<>(urm)); }
- 方式二:关联数据修改后,重新查询一次User对象,依赖EAGER加载自动拉取关联数据:
// 保存完关联数据后加一行 user = usersRepository.findByPhoneNumber(phone);
问题2:Role_info去掉嵌套User对象方案
两种实现方式,根据场景选择:
快速实现(适合测试场景)
在UserRoleMapping类的user属性上添加@JsonIgnore注解,序列化时自动忽略该字段:
import com.fasterxml.jackson.annotation.JsonIgnore; @ManyToOne @JoinColumn(name = "user_id") @JsonIgnore User user;
规范实现(适合生产环境)
自定义DTO类只返回需要的字段,不直接暴露实体类给接口:
// 定义DTO @Data public class UserRoleDTO { private Integer id; private Role role; } // 接口返回时转换 UserRoleDTO roleDTO = new UserRoleDTO(); roleDTO.setId(userRoleMapping.getId()); roleDTO.setRole(userRoleMapping.getRole()); result.put("Role_info" ,roleDTO);
内容的提问来源于stack exchange,提问作者njari
相关产品推荐
相关产品推荐

