3

This question has been asked a lot and many people use @JsonInclude(JsonInclude.Include.NON_NULL)

This however doesn't seem to work for me.

What I have is a Trainer and a Course. A trainer has a list of courses and a course has a list of trainers. The java objects are shown here below:

@Entity
@Table(name="TRAINER")
@JsonInclude(JsonInclude.Include.NON_NULL)
public class Trainer {

 //Lots of other properties

  @ElementCollection
  @ManyToMany(cascade = CascadeType.MERGE, fetch = FetchType.LAZY)
  @JsonProperty(access = JsonProperty.Access.WRITE_ONLY)
  @JoinTable(
          name="COURSE_TRAINERS",
          joinColumns=@JoinColumn(name="ID_TRAINER", 
          referencedColumnName="ID"),
          inverseJoinColumns=@JoinColumn(name="ID_COURSE", 
          referencedColumnName="ID"))
  private List<Course> courses;

  // constructors

  // getters and setters annotated with @NoTNull
}

And now my course class

@Entity
@Table(name="COURSE")
@JsonInclude(JsonInclude.Include.NON_NULL)
public class Course {

  // other properties

  @ElementCollection
  @ManyToMany(cascade = CascadeType.MERGE, fetch = FetchType.LAZY)
  @JsonProperty(access = JsonProperty.Access.WRITE_ONLY)
  @JoinTable(
        name="COURSE_TRAINERS",
        joinColumns=@JoinColumn(name="ID_COURSE", 
        referencedColumnName="ID"),
        inverseJoinColumns=@JoinColumn(name="ID_TRAINER", 
        referencedColumnName="ID"))
  private List<Trainer> trainers;

  //getters and setters annotad with @NotNull

}

Whenever we send a Put request to the server to update a Course, we don't send along it's list of trainers. So its json looks like this:

{
"id":1,
"name":"Agile Introduction",
"min_trainees":1,
"max_trainees":11,
"target_group":"General",
"course_details":"Long description dummy text.","active":true
}

We annotate the property 'courses' and 'trainers' with JsonProperty.Access.WRITE_ONLY to prevent to send the entire list along with a course or a trainer.

So does anyone know why when we send the above JSON, all of our trainers are gone within a course?

Wouter Vandenputte
  • 1,948
  • 4
  • 26
  • 50
  • 1
    Looks like the root problem is that you have bidirectional references between the objects. Have a look at `@JsonIdentityInfo` in this other answer and see if that works for you http://stackoverflow.com/questions/37302816/how-to-use-jsonidentityinfo-with-circular-references – coladict May 18 '17 at 09:21

0 Answers0