Reputation:
Hello is it possible to add mapped value in json?
Product entity
@Id
@Column(unique = true)
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
@Column(unique = true)
private String title;
private String description;
@OneToMany(fetch = FetchType.LAZY)
private List<Options> options= new ArrayList<>();
Option entity
@Id
@Column(unique = true)
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
@ManyToOne(fetch = FetchType.EAGER)
@OnDelete(action = OnDeleteAction.CASCADE)
@JsonIgnore
private Product product;
private BigDecimal price=new BigDecimal(0);
private BigDecimal discount=new BigDecimal(0);
What i get is
{
"id": 2,
"price": 300.00,
"discount": 35.00
},
What i want is
{
"id": 2,
"price": 300.00,
"discount": 35.00,
"product":[
"id": 2,
"title": "dsfa",
"description": "dsfa",
....
]
},
I want to add product to json response, how can i achieve this?
Upvotes: 1
Views: 654
Reputation: 729
Yes, just use @JsonIgnoreProperties
.
@Id
@Column(unique = true)
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
@Column(unique = true)
private String title;
private String description;
@OneToMany(fetch = FetchType.LAZY)
@JsonIgnoreProperties(value = {"product"})
private List<Options> options= new ArrayList<>();
and second class:
@Id
@Column(unique = true)
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
@ManyToOne(fetch = FetchType.EAGER)
@OnDelete(action = OnDeleteAction.CASCADE)
@JsonIgnoreProperties(value = {"options"})
private Product product;
private BigDecimal price=new BigDecimal(0);
private BigDecimal discount=new BigDecimal(0);
You will avoid the infinity loop in json result and get all reference objects (relationships).
Upvotes: 1
Reputation: 31
One Product have many Option or viceversa? In your code one Product have many Option.
But if the relation is correct, the better way to get a custom result is with DTOs.
With DTO you can create a custom Class with all the details you need, example:
ProductDTO
private Integer id;
private String title;
private String description;
getter / setter
OptionDTO
private Integer id;
private BigDecimal price=new BigDecimal(0);
private BigDecimal discount=new BigDecimal(0);
private List<Product> products;
getter / setter
Soo, first retrieve with you service and reposity you data, then you set the DTO.
After you can send you data and get your custom Json.
Upvotes: 1