Juan Pablo
Juan Pablo

Reputation: 314

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.

Upvotes: 2

Views: 1152

Answers (2)

DurandA
DurandA

Reputation: 1559

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

Upvotes: 1

Catchwa
Catchwa

Reputation: 5855

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:

Upvotes: 2

Related Questions