Relationship between Rest Resources with Spring boot

Asked

Viewed 345 times

2

I’m learning Spring Boot Rest and with a doubt I can’t solve on my own, you could help me?

I created the following mapping between Launch and Person entities:

Entidade Pessoa:

   @Entity
   public class Pessoa {

    ...

    @JsonIgnore
    @OneToMany(mappedBy="pessoa")
    private List<Lancamento> lancamentos;
    //getters setters
    }

Entidade Lancamento:

@Entity
@Table(name="lancamento")
public class Lancamento {
...
@NotNull
@ManyToOne
@JoinColumn(name="id_pessoa")
private Pessoa pessoa;
//getters setters
}

Expected Result:

{
  "nome":"Pessoa1",
   lancamentos:[
         {
           "id":"1",
           "descricao":"Educacao"
         },
         {
          "id":"2",
          "descricao":"Alimentacao"
         },
       ]
}

Result Obtained:

{
  "nome":"Pessoa1"
}

What am I doing wrong?

  • Anna, try to remove this @Jsonignore annotation and forehead. It may be that this is preventing (ignoring) this attribute. Something else. You have all the getters and setters created?

  • 1

    Hello Danilo, when I take @Jsonignore from the circular dependency error and na is returned in the request, and I created all getters and setters as well.

1 answer

2

I found the solution in the Post https://stackoverflow.com/questions/3325387/infinite-recursion-with-jackson-json-and-hibernate-jpa-issue , that gave me the expected result. Just use the Annotations @JsonManagedReference and @JsonBackReference of Jackson.

The code went like this:

Entidade Pessoa:

   @Entity
   public class Pessoa {

    ...
    @JsonManagedReference
    @JsonIgnore
    @OneToMany(mappedBy="pessoa")
    private List<Lancamento> lancamentos;
    //getters setters
    }

Entidade Lancamento:

@Entity
@Table(name="lancamento")
public class Lancamento {
...
@JsonBackReference
@NotNull
@ManyToOne
@JoinColumn(name="id_pessoa")
private Pessoa pessoa;
//getters setters
   }

Browser other questions tagged

You are not signed in. Login or sign up in order to post.