在拥有@ManyToMany关系的JPA Spring Boot应用中,避免循环冗余的方法是使用@JsonIgnore注解或者使用DTO(Data Transfer Object)来解决。
@Entity
public class User {
// ...
@ManyToMany
@JsonIgnore
private List<Role> roles;
// ...
}
@Entity
public class Role {
// ...
@ManyToMany(mappedBy = "roles")
@JsonIgnore
private List<User> users;
// ...
}
@Entity
public class User {
// ...
@ManyToMany
private List<Role> roles;
// ...
}
@Entity
public class Role {
// ...
@ManyToMany(mappedBy = "roles")
private List<User> users;
// ...
}
public class UserDTO {
private Long id;
private String username;
// ...
public UserDTO(User user) {
this.id = user.getId();
this.username = user.getUsername();
// ...
}
// getters and setters
}
@RestController
public class UserController {
// ...
@GetMapping("/users/{id}")
public UserDTO getUserById(@PathVariable Long id) {
User user = userRepository.findById(id).orElse(null);
if (user != null) {
return new UserDTO(user);
}
return null;
}
// ...
}
通过使用上述方法,可以在拥有@ManyToMany关系的JPA Spring Boot应用中避免循环冗余,提高数据传输效率,并且更好地控制返回给前端的数据。
领取专属 10元无门槛券
手把手带您无忧上云