首页 > 解决方案 > How not to get the colletion in @ManyToMany in hibernate/springboot?

问题描述

I have 3 tables, Company, Coupon, Customer. Many companies should have many coupons, many customers should have many coupons.

everything is working fine, besides the fact that I don't want to get the coupons collection when I'm calling Coupon/Customer.

I'm using Swagger to test the application, and I'm getting the Coupons collection upon the Customer/ Company.

I did try to add LAZY fetch type, and it did not work, I'm not actually sure how to call this.

I don't want to get the Coupon collection when calling a Company.

@Entity
public class Company {

@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column
private long id;
@ManyToMany
private List<Coupon> coupons;
private String name;
private String email, password;

public Company() {

}

public Company(long id, String name, String email, String password) {
    this.id = id;
    this.name = name;
    this.email = email;
    this.password = password;
}


@Entity
public class Coupon {

@Id
@GeneratedValue
@Column
private long id;
private String title;
private String message;
private double price;
private int amount;

@Enumerated(EnumType.STRING)
@Column(columnDefinition = "varchar(32) default 'OTHER'")
private CouponType type = CouponType.OTHER;
@Enumerated(EnumType.STRING)
@Column(columnDefinition = "varchar(32) default 'SALE'")
private CouponStatus status = CouponStatus.SALE;

And this is the JSON I'm getting when calling a company in swagger

{
  "id": 2,
  "coupons": [],
  "name": "Macdonalds",
  "email": "Macdonalds",
  "password": "123"
}

标签: javajsonspringspring-bootspring-data-jpa

解决方案


If you don't want it to be serialized when creating json (default in springboot), you need to exclude it. In jackson simply annotate it with @JsonIgnore:

@JsonIgnore
@ManyToMany
private List<Coupon> coupons;

In gson on the other hand, you would have to annotate every other field with @Expose.


推荐阅读