is there any way to fetch data from many to many tables using spring without infinite json format?

Tags: , , , ,



user entity

@Id@GeneratedValue(strategy = GenerationType.AUTO)
Integer id;
// ... more properties

@ManyToMany(cascade = {CascadeType.ALL})
@JoinTable(name = "User_Boards", joinColumns = {@JoinColumn(name = "user_id")}, inverseJoinColumns = {@JoinColumn(name = "board_id")})
Set < Board > user_board = new HashSet < >();
//getter and setter and constructors

board entity

@Entity
public class Board  implements Serializable{

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    int  id;
    String name;
    int P_id;
    @ManyToMany(mappedBy = "user_board" , fetch = FetchType.LAZY)
    Set<User> users_of_board = new HashSet<>();
//getter and setter and constructors

When I try to fetch data using findAll method I get infinite json object.

For example when I fetch users I have set of boards inside it I have set of users and inside it I have set of boards… etc.

How can I fetch user with his boards and boards with its users ?

Answer

You can use @JsonBackReference in the class where you don’t want to get the linked object.

So, if I’ve not missunderstood, one user has many boards, and a board owns to an user or many, so fetching one user you get an infinite recursion.

So into Board class you have to do:

@ManyToMany(mappedBy = "user_board" , fetch = FetchType.LAZY)
@JsonBackReference //<--- Add this
Set<User> users_of_board = new HashSet<>();

And then, the object will not be infinite.

Also you can check this article.



Source: stackoverflow