INFINITE LOOP HIBERNATE APIREST

0

hi how I am currently doing a project with these technologies

  • HIBERNATE (TO CREATE ENTITIES AND DEMAS)
  • JPA (ETC. CONNECTIONS)
  • JDBC (CONNECTIONS OF ANOTHER TYPE)
  • SPRING MVC (TO CREATE THE DRIVER AND RETURN JSON)

The detail is that I have very little experience with hibernate ..

I currently have this kind of example in relations @onetomany

@Entity
public class Recetas implements Serializable {
    @GeneratedValue(strategy = GenerationType.AUTO)
    @Id
    private int id;
    private String Nombre;
    private String imagenUrl;
    private int minutos;
    @OneToMany(mappedBy = "recetas_id")
    private List<Ingredientes> ingredientes = new ArrayList<>();

that makes a relation with ingredients (since a recipe can have several ingredients)

 @Entity
public class Ingredientes {
    @GeneratedValue(strategy = GenerationType.AUTO)
    @Id
    private int id;
    private String nombre;
    @ManyToOne
    @JoinColumn(name = "recetas_id", nullable = false)
    private Recetas recetas_id;

and I do a joincolumn for references to the father and have a bidirectional relationship of

The detail is that when I try to extract the data in json it makes me an infinite loop

because as you can see a father has a son and the son refers to the father .. and then a loop is made inward

{
    "id": 1,
    "nombre": "Huevos",
    "recetas_id": {
        "id": 1,
        "imagenUrl": "http://google.com.mx",
        "minutos": 10,
        "ingredientes": [],
        "nombre": "Huevos con chorizo "
    }
}
    
asked by Monster 02.06.2018 в 17:27
source

1 answer

1

The way to avoid what you are saying is indicating which attributes you do not want included in the JSON response. For this there are several options, but the simplest one is to use the annotation com.fasterxml.jackson.annotation.JsonIgnore (it is in the package com.fasterxml.jackson.core: jackson-annotations: 2.9.5 )

Your entity would remain like this:

@Entity
public class Ingredientes {
    @GeneratedValue(strategy = GenerationType.AUTO)
    @Id
    private int id;
    private String nombre;

    @JsonIgnore
    @ManyToOne
    @JoinColumn(name = "recetas_id", nullable = false)
    private Recetas recetas_id;

    ....
}

The Spring driver, when it comes to processing the object to be returned as JSON, upon finding that annotation, will ignore the attribute.

Another option would be for you to create some DTOs, in which you did not have that son-> father relationship and those DTOs that you returned, creating them from the entities that you have recovered via JPA, although I am more in favor of use the annotation.

PS: Notice that just as you have designed the entities, a recipe has several ingredients, but an ingredient can only be in one recipe.

    
answered by 02.06.2018 / 23:21
source