Reputation:
I have an entity called User with these fields :
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "user_id")
private Long id;
@Column(name = "name")
private String name;
@Column(name = "last_name")
private String lastName;
@OneToMany(mappedBy="userId")
private List<Survey> survey= new ArrayList<>();
And the Survey entity which has :
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "SURVEY_ID")
private Long Id;
@ManyToOne
@JoinColumn(name = "user_id",referencedColumnName="user_id")
private User userId;
.....
I want one User to be have many Surveys, and each survey is related to one user. But there is something wrong with the way I've mapped it, cuz as JSON file, when I access allUsers I get this :
[{"id":1,"name":"User","lastName":"user","email":"[email protected]","surveyData":[{"userId":{"id":1,"name":"User","lastName":"user","email":"[email protected]","surveyData": ,...... and repeats itself
So instead of getting as list the values of the survey data, I get the values of the Users information ? Can someone help me with this ?
Upvotes: 1
Views: 460
Reputation: 5105
Your mapping is correct.
Just use @JsonManagedReference
in your User class and @JsonBackReference
in your Survey Class. @JsonManagedReference
is the forward part of reference – the one that gets serialized normally. @JsonBackReference
is the back part of reference – it will be omitted from serialization.
In the User Class:
@OneToMany(mappedBy="userId")
@JsonManagedReference
private List<Survey> survey;
In the Survey Class:
@ManyToOne
@JoinColumn(name = "user_id",referencedColumnName="user_id")
@JsonBackReference
private User userId;
I have 2 remarks:
userId
in the Survey class to user
, since it is a User object and no identifier. Upvotes: 3