Пружинная загрузка, включите отношение «один ко многим» в ответ Json с обеих сторон - PullRequest
0 голосов
/ 27 октября 2019

У меня есть две сущности, продукт и категория с отношением oneToMany. У каждого товара есть одна категория, а у корзины может быть несколько товаров.

Я могу показать список товаров в JsonResponse со стороны категории, но не со стороны товара. Что мне не хватает?

-JsonResponse при использовании Получение категории по категорииName:

{
   "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 при использовании Получение продукта по productReference:

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

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

Я хочу получить это:

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

-Категория объекта:

@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...    

}

-Сущность продукта:

@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...   

}

1 Ответ

0 голосов
/ 27 октября 2019

Вы не можете видеть свойство categorie, потому что оно аннотировано @JsonIgnore.

Но если вы удалите эту аннотацию, вы получите бесконечный цикл при сериализации вашего объекта ... Здесь - хорошая статья о возможных решениях / обходных путях.

...