java - Recursive JSON view of an entity with one-to-many relationship in REST controller -


i'm using springboot , jpa build rest interface.

now, have strange json returned list of products fetched database. let's 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 product defined as:

public interface productrepository extends jparepository<product, long> {     list<product> findall(); } 

in controller have:

@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 driving crazy, if try call service follows:

$ curl localhost:8080/all-products 

i recursive output due relationship between tables product , category, e.g.:

{"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 doing wrong?

you're not doing wrong (at least @ code level it's rather conceptual) - json serializer goes this:

  1. product - serialize it, wait - there category field, serializer must serialize category field
  2. category - serialize it, wait - there products field, serializer must serialize each of product in list
  3. product - because collection contains product & product contains category goes in endless loop untill timeout.

you must use view or skip it.

  1. use @jsonview

  2. use view pojo return new productview has fields of product , reference (category) new categoryview (you can end @ point) has collection of (products) new productviewwithoutreferences, , on

  3. use @jsonignore on collection of products

and side note - if it's @restcontroller , you're invoking "all-products" it's bit unusual return else list. wrapping response in map redundant. many rest clients expect list when invoke list() method.


Comments

Popular posts from this blog

php - Zend Framework / Skeleton-Application / Composer install issue -

c# - Better 64-bit byte array hash -

python - PyCharm Type error Message -