gpt4 book ai didi

java - spring-boot JPA无限循环多对多

转载 作者:行者123 更新时间:2023-12-05 01:29:19 27 4
gpt4 key购买 nike

我有两个实体,它们是多对多关系。

@Entity
public class Room {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private long id;

@ManyToMany(mappedBy = "rooms")
private Set<Team> teams;
}
@Entity
public class Team {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private long id;

@ManyToMany
@JoinTable(name = "teams_rooms",
joinColumns = @JoinColumn(name= "team_id"),
inverseJoinColumns = @JoinColumn(name = "room_id"))
private Set<Room> rooms;

}

为了生成数据,我有一个“房间”和“团队”的存储库:

public interface RoomRepository extends CrudRepository<Room, Long> {
}
public interface TeamRepository extends CrudRepository<Team, Long> {
}

我的目标是请求一个团队的所有房间,但要防止 JPA 无限循环。

@RestController
@RequestMapping("....")
public class RoomController {
@Autowired
private RoomRepository roomRepository;

@GetMapping
public Iterable<Room> getAllRoomsOfTeam() {
final long exampleId = 1; //This is just a placeholder. The id will be passed as a parameter.

final var team = teamRepository.findById(exampleId);

return ResponseEntity.ok(team);
}
}

这是结果:

{
"id": 1,
"name": "Team1",
"rooms": [
{
"id": 1,
"name": "Room 1",
"teams": [
{
"id": 1,
"name": "Team 1",
"rooms": [
{
"id": 1,
"name": "Room 1",
"teams": [

Jackson 将永远循环,直到发生异常(因为反向引用也引用了父元素,这将创建一个循环)。我已经尝试过 @JsonManagedReference@JsonBackReference,但它们用于多对一关系。

如何阻止 Jackson 无限循环?我想尽可能少地影响其他存储库和查询。

最佳答案

您的 Controller 不应返回实体(带有@Entity 注释的类)。最佳做法是创建另一个具有相同属性的单独类。这段代码有一点重复,但它保持了所有层的清洁。我还建议使用@Service。

   public class RoomDTO { 
private String name;
private List<TeamDTO> teams = new ArrayList<>();

public RoomDTO() {
}

public RoomDTO(Room room) {
this.name = room.name;
for(Team team : room.getTeams()) {
TeamDTO teamDTO = new TeamDTO();
teamDTO.setName(team.getName);
teams.add(teamDTO);
}
}
}



public class TeamDTO {
List<RoomDTO> rooms = new ArrayList();

public TeamDTO() {
}

public TeamDTO(Team team) {
this.name = team.name;
for(Room room : team.getRooms()) {
RoomDTO roomDTO = new RoomDTO();
roomDTO.setName(team.getName);
rooms.add(roomDTO);
}
}

}

Controller 应该返回这个

@GetMapping
public Iterable<TeamDTO> getAllRoomsOfTeam() {
final long exampleId = 1;
final var team = teamRepository.findById(exampleId);

TeamDTO teamDTO = new TeamDTO(team);

return ResponseEntity.ok(teamDTO);

How to use DTOs in the Controller, Service and Repository pattern

关于java - spring-boot JPA无限循环多对多,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67886252/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com