I got a problem with a maven Spring project, started with Springboot. My problem is when I call a method of a controller, it returns some fields that I don't want.
For example, "Pays" (=country) is related to "Departement" (Department) with a OneToMany (one Pays got many Departements)
Here's my Entity :
@Entity
@Table(name = "pays")
public class Pays {
public interface DefaultView {}
@Id
@JsonView(DefaultView.class)
private Long id;
@JsonView(DefaultView.class)
private String nom;
@OneToMany(mappedBy = "pays")
private List<Departement> departements;
public Pays(Long id, String nom) {
this.id = id;
this.nom = nom;
}
public Pays() {
}
public Long getId() {
return id;
}
public String getNom() {
return nom;
}
public List<Departement> getDepartements() {
return departements;
}
public void setNom(String nom) {
this.nom = nom;
}
public void setDepartements(List<Departement> departements) {
this.departements = departements;
}
}
and this controller :
@RestController
@RequestMapping(value = "/ws/pays")
public class PaysController {
@Autowired
private PaysService paysService;
@RequestMapping("/default")
@JsonView(Pays.DefaultView.class)
public List<Pays> getPayss() {
return paysService.findAll();
}
}
Everytime I go to /ws/pays/default - and call "getPayss()" -, it makes an infinite loop, trying to call the "Departements" of the "Pays", and the "Pays" of each "Departement", and so on...
For this example, I don't need the "Departements" of a "Pays", so I could use @JsonIgnore, but I don't want to, because for other calls, I will need the "Pays" of a "Departement"
Does anyone has a solution to fetch and serialize only the "id" and "nom" of my object "Pays" for this example ?
FYI, here's a sample of my Entity "Departement" :
@Entity
@Table(name = "departement")
public class Departement {
@Id
private Long id;
private String nom;
private String code;
private String soundex;
@ManyToOne
@JoinColumn(name = "id_pays")
private Pays pays;
//Getters and setters are properly declared, but not shown here to preserve space
}
Thanks a lot