Recursive JSON view of a one-to-many relationship object in a REST controller

I use SpringBoot and JPA to create a REST interface.

Now I have weird JSON returned for a list of products retrieved from the database. Let's say that I have:

@Entity
public class Product {

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

    @ManyToOne(optional = false, fetch = FetchType.LAZY)
    @JoinColumn(name = "categoryId", nullable = false, updatable = false)
    private Category category;

    ...
}

@Entity
public class Category implements Serializable {

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

    @OneToMany(mappedBy = "category", cascade = CascadeType.DETACH)
    @OrderBy("name ASC")
    private List<Product> products = Collections.emptyList();

    ...
}

The JPA repository for Productis defined as:

public interface ProductRepository extends JpaRepository<Product, Long> {
    List<Product> findAll();
}

In my controller, I:

@Autowired
private ProductRepository productRepo;

@RequestMapping("/all-products", method = RequestMethod.GET)
public Map<String,Object> home() {
    Map<String,Object> model = new HashMap<String,Object>();
    model.put("products", productRepo.findAll());
    return model;
}

What drives me crazy is that if I try to name this service as follows:

$ curl localhost:8080/all-products

I get recursive output due to the relationship between tables Productand categoryfor example:

{"products":[{"id":1,"name":"Product1","category":
{"id":1,"name":"Cat1","products":[{"id":6,"name":"Product6","category":
{"id":1,"name":"Cat1","products":[{"id":6,"name":"Product6","category":
{"id":1,...

What am I doing wrong?

+4
source share
3 answers

( , ) - json serializer :

  • - , - ,
  • - , - ,
  • - , , .

.

  • @JsonView

  • POJO new ProductView, () new CategoryView ( ), () new ProductViewWithoutReferences ..

  • @JsonIgnore

- a @RestController, " ", - , . . , list().

+9

, , - . , ,

fooobar.com/questions/85901/...

Jackson 1.6 , . http://wiki.fasterxml.com/JacksonFeatureBiDirReferences.

, , JSON (jackson, gson flex-json at ), , ( ), . , .

EDIT ( 2012): Jackson 2.0 true , .

0

@JsonIgnore

@OneToMany(mappedBy = "policy")
@JsonIgnore
private List<Payment> payments;

@JeanValjean

0
source

Source: https://habr.com/ru/post/1598297/


All Articles