Search code examples
jsonspringhibernatejpapersist

I'm using Spring MVC and JSON to do some tasks, and i've got this exception


I've been searching for three days, and my error still exist, I've tried a lot of solutions without any positive result !

I've ManyToMany relations, and here is my JPA mapping :

@Entity public class Facteur implements Serializable {

/**
 * 
 */
private static final long serialVersionUID = 1L;

@Id
@GeneratedValue(strategy=GenerationType.AUTO)
private Long idF;

.....

@ManyToMany
@LazyCollection(LazyCollectionOption.FALSE)
@JoinTable(name="Affectation",joinColumns=@JoinColumn(name="IdF"), inverseJoinColumns=@JoinColumn(name="idT"))
private List<Tournee> tournees;

.......

}

"Tournee" Class is like this

@Entity public class Tournee implements Serializable {

@Id
@GeneratedValue(strategy=GenerationType.AUTO)
private int idT;

....
@ManyToMany(mappedBy="tournees")
@LazyCollection(LazyCollectionOption.FALSE)
private List<Facteur> facteurs;

....

}

here is my controller :

@RequestMapping(value="/getFacteur/", method=RequestMethod.GET)
@ResponseBody
public Facteur getFacteurById(@RequestParam("id") Long idF) {
    Facteur f = facteurService.getById(idF);
    System.out.println(f.toString());
    return f;
}

and JQuery code is :

$(document).ready(function() {
        $(".updatelink").click(function() {
            var facteurId = $(this).data("facteur-id");
            $.ajax({
                type : "GET",
                url : "http://localhost:8080/distribution/facteur/getFacteur/",
                data : { id : facteurId },
                success : function(data) {
                            alert('SUCCESSS');
                            },
                error : function(){
                            alert("ERROR");
                }
            });
        });
    });

Any solutions ?

Best regards !


Solution

  • One of the two sides of the relationship should not be serialized in order to avoid the infinite loop that causes your stackoverflow error. You can use @JsonManagedReference and @JsonBackReference to avoid the error:

    //class Facteur
    @ManyToMany
    @LazyCollection(LazyCollectionOption.FALSE)
    @JoinTable(name="Affectation",joinColumns=@JoinColumn(name="IdF"), inverseJoinColumns=@JoinColumn(name="idT"))
    @JsonManagedReference
    private List<Tournee> tournees;
    
    //class Tournee
    @ManyToMany(mappedBy="tournees")
    @LazyCollection(LazyCollectionOption.FALSE)
    @JsonBackReference
    private List<Facteur> facteurs;
    

    Add the @JsonManagedReference in the forward part of the relationship which you want to serialize, and add @JsonBackReference in the back part of the relationship which will not be serialized. In fact, if you serialize a Tournee instance to JSON, you will not get the Facteur array instance. To avoid this drawback, just use the simple @JsonIgnore, but keep in mind, that therefore getters and setters will be ignored during serialization.