2

I am facing a issue.. I have a many to many relationship with jpa in spring boot, but I need to expose the following product has many tags and tag has many product

if query product/1

{product:{name:"product 1"}, tags:[ tag1:{name:"tag 1"}, tag2:{name:"tag2"} ] }

if query tag/1

{tag:1, products:[ product1:[{name:"product 1"}, tag2:{product:"tag2"} ] }

what is the way to expose this with rest with spring boot? a example, url or and idea it would be useful.

Juan Pablo
  • 304
  • 3
  • 8
  • 1
    not sure what you wanted.. are you looking for a way to map these to JPA entities? – Ish Oct 06 '17 at 04:48
  • ah sorry I already have the mapping working , but maybe u know when you try to expose it as rest (converted to json) there is a infinite recursion exception , because the both sides relationship.. what i am looking is a new point of view to expose it as rest like my example, maybe I am not facing well the problem and there is a best way – Juan Pablo Oct 06 '17 at 04:58
  • Try this link: http://www.baeldung.com/jackson-bidirectional-relationships-and-infinite-recursion – Ish Oct 06 '17 at 05:11
  • 1
    So if you have the JPA mapping working then the problem is nothing to do with JPA, and everything to do with JSON, so remove the `JPA` tag from the question –  Oct 06 '17 at 07:22

2 Answers2

2

You need to use a combination of @JsonManagedReference and @JsonBackReference annotations to stop an infinite recursion from occurring when you try and serialise your JPA beans.

Have a look at some of these questions for further info:

Catchwa
  • 5,845
  • 4
  • 31
  • 57
1

There are multiple alternatives to stop infinite recursion:

  1. @JsonManagedReference and @JsonBackReference:
@Entity
public class Product {
    @ManyToMany
    @JsonManagedReference
    private List<Tag> tags = new ArrayList<Tag>();
}

@Entity
public class Tag implements {
    @ManyToMany(mappedBy = "tags")
    @JsonBackReference
    private List<Product> products = new ArrayList<Product>();
}
  1. @JsonIdentityInfo:
@Entity
public class Product {
    @ManyToMany
    private List<Tag> tags = new ArrayList<Tag>();
}

@JsonIdentityInfo(generator = ObjectIdGenerators.PropertyGenerator.class, property = "id")
@Entity
public class Tag implements {
    @ManyToMany(mappedBy = "tags")
    private List<Product> products = new ArrayList<Product>();
}
  1. @JsonIgnoreProperties:
@Entity
public class Product {
    @ManyToMany
    @JsonIgnoreProperties("products")
    private List<Tag> tags = new ArrayList<Tag>();
}

@Entity
public class Tag implements {
    @ManyToMany(mappedBy = "tags")
    @JsonIgnoreProperties("tags")
    private List<Product> products = new ArrayList<Product>();
}
DurandA
  • 1,095
  • 1
  • 17
  • 35