Site icon NgDeveloper

Understanding @JsonIgnore with JPA Hibernate

Understanding @JsonIgnore with JPA Hibernate

@JsonIgnore

 

I have Coupon and Category Model with Many to Many mapping:

Here in coupon model I have category model with many to many mapping along with JsonIgnore annotation. So Here when I try to save coupon model then categories also saved, but When I try to retrieve coupon model then the categorylist is missing in the json response.

If you remove @JsonIgnore annotation from categoryList field then the category lists attribute will be available inside every coupons.

 

Coupon.java:

[java]
@Entity
public class Coupon implements Serializable{

public Coupon(){
}

@ManyToMany
@JsonIgnore
private Set categoryList;

public Set getCategoryList() {
return categoryList;
}

public void setCategoryList(Set categoryList) {
this.categoryList = categoryList;
}
}
[/java]

 

Category.java:

 

[java]
@Entity
public class Category implements Serializable{
public Category(){
}

@ManyToMany(mappedBy=”categoryList”)
private Set coupon;

public Set getCoupon() {
return coupon;
}

public void setCoupon(Set coupon) {
this.coupon = coupon;
}
}
[/java]

 

Now If I try to get the category list through coupon, then I am not getting anything in the JSON response, due to @JsonIgnore annotation.

So removed @JsonIgnore and the final coupon model is:

Coupon [After Removing @JsonIgnore for categoryList]

[java]
@Entity
public class Coupon implements Serializable{

public Coupon(){
}

@ManyToMany
private Set categoryList;

public Set getCategoryList() {
return categoryList;
}

public void setCategoryList(Set categoryList) {
this.categoryList = categoryList;
}
}
[/java]

When to use @JsonIgnore ?

When you want to hide attributes from the Jackson Parser then use @JsonIgnore to the field which you do not want. You can also use @JsonIgnoreProperties for the same.

My Coupon Response with @JsonIgnore:

Here categoryList attribute does not appear in the JSON due to @JsonIgnore annotation for categoryList attribute.

[plain]
[{“couponId”:2043,”couponTitle”:”Buy 3 Tshirts At Rs. 279/-“,”created_date”:1504882385000}]
[/plain]

 

 

My Coupon Response without @JsonIgnore:

Here categoryList attribute appears in the JSON, here still no value, but atleast that attribute or field appears.

[plain]
[{“couponId”:2043,”couponTitle”:”Buy 3 Tshirts At Rs. 279/-“,”categoryList”:[],”created_date”:1504882385000}]
[/plain]

 

I am trying to understand more details and differences between @JsonIgnore and @JsonIgnoreProperties, I will let you guys know once I found!

Exit mobile version