简体   繁体   中英

How to expose many to many relationship in spring boot

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.

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:

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>();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM