Spring-boot JPA无限循环多对多

pgccezyw  于 11个月前  发布在  Spring
关注(0)|答案(2)|浏览(190)

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

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

    @ManyToMany(mappedBy = "rooms")
    private Set<Team> teams;
}

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

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无限循环?我希望尽可能少地影响其他存储库和查询。

42fyovps

42fyovps1#

你的控制器不应该返回entities(带有注解@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);
            }
        }
        
   }

字符串
控制器应该返回这个

@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

voase2hg

voase2hg2#

目前,在您的类中存在循环依赖,这导致在将对象转换为JSON时出现问题。请在Team类中的rooms变量上添加@JsonIgnore注解,如以下示例所示:

import com.fasterxml.jackson.annotation.JsonIgnore;

@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"))
    @JsonIgnore
    private Set<Room> rooms;

}

字符串
如果你需要一个双向转换的解决方案,那么你可以使用JsonView注解。
首先,您需要为TeamRoom创建JSON视图配置文件,如以下示例所示:

public class JsonViewProfiles
{
    /**
     * This profile will be used while converting Team object to JSON
     */
    public static class Team {}

    /**
     * This profile will be used while converting Room object to JSON
     */
    public static class Room {}
}


在实体中使用上面创建的JSON视图配置文件,如下面的示例所示:

public class Room {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    @JsonView({ JsonViewProfiles.Team.class, JsonViewProfiles.Room.class })
    private long id;

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

    @ManyToMany
    @JoinTable(name = "teams_rooms",
        joinColumns = @JoinColumn(name= "team_id"),
        inverseJoinColumns = @JoinColumn(name = "room_id"))
    @JsonView(JsonViewProfiles.Team.class)
    private Set<Room> rooms;
}

的字符串
在将对象转换为JSON时,请使用以下示例中所示的配置文件:

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

    final Team team = teamRepository.findById(exampleId);

    String result = new ObjectMapper().writerWithView(JsonViewProfiles.Team.class)
                .writeValueAsString(team);

    return result;
}

相关问题