chedli chris
chedli chris

Reputation: 23

Spring boot , include one-to-many relation in Json response from both sides

I have two entities , product and category with a relation of oneToMany . Each product have one category and a cagetory can have multiple products .

I can show the list of products in the JsonResponse from the category side but not from the product side . What I'm I missing ?

-JsonResponse when using Getting a category by categoryName :

{
   "id": 1,
   "reference": "cat1",
   "name": "electornique",
   "produits": [
      {
         "id": 2,
         "reference": "tab1",
         "designation": "ordinateurupdate",
         "price": 600,
         "quantite": 1234
      },
      {
         "id": 3,
         "reference": "tel1",
         "designation": "tel 1 was updated",
         "price": 600,
         "quantite": 1234
      },
      {
         "id": 4,
         "reference": "ord2",
         "designation": "ordinateur",
         "price": 400,
         "quantite": 3
      }
   ]
}

JsonResponse when using Getting a product by productReference :

URL : http://localhost:8080/api/produits/ord2

{
   "id": 4,
   "reference": "ord2",
   "designation": "ordinateur",
   "price": 400,
   "quantite": 3
}

I want to acheive this :

{
   "id": 4,
   "reference": "ord2",
   "designation": "ordinateur",
   "price": 400,
   "quantite": 3,
   categorie : { id : "" , reference : "", name: "" }
}

-Category entity :

@Entity
@Table(name="categorie",indexes = {@Index (name="index_categorie_reference",columnList="reference",unique= true),
                                   @Index(name="index_categorie_name",columnList="name",unique= true)

})

public class Categorie implements Serializable {


    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @Column(unique = true)
    private String reference;

    @Column(unique= true)
    private String name;


    @OneToMany(mappedBy= "categorie")
    private List<Produit> produits;


// getters and setters...    

}

-Product entity :

@Entity
@Table(name="produit",indexes = {@Index (name="index_produit_reference",columnList="reference",unique= true)})
public class Produit  implements Serializable{

  @Id
  @GeneratedValue(strategy = GenerationType.IDENTITY)
  private Long id;

  @Column(unique = true)
  private String reference;

  private String designation;
  private double price;
  private int quantite;



  @ManyToOne(fetch = FetchType.LAZY)
  @JoinColumn(name="categorie_id") 
  @JsonIgnore
  private Categorie categorie;


  public Produit() {

  }


// getters and setters...   

}

Upvotes: 0

Views: 5524

Answers (1)

Selindek
Selindek

Reputation: 3423

You cannot see the categorie property because it's annotated with @JsonIgnore.

But if you remove that annotation, you will get an infinite loop when serializing your object... Here is a good article about the possible solutions/workarounds.

Upvotes: 2

Related Questions