java - Spring: When getting a ManyToOne entity, reference entity (OneToMany) is not showing in JSON -
when send request in postman child entity (town) parent entity (province) not shown in json response.
this controller.
@requestmapping(value ="api/v1/town",method = requestmethod.get) public responseentity<list<town>> getalltowns() { list<town> towns = townservice.getalltowns(); if(towns.isempty()) { return new responseentity<list<town>>(httpstatus.no_content); } return new responseentity<list<town>>(towns, httpstatus.ok); }
and these entities.
parent class
@entity @table(name = "province") public class province { @id @generatedvalue(strategy = generationtype.auto) @column(name = "province_id") private long id; private string name; @onetomany(fetch = fetchtype.lazy, cascade = cascadetype.all, mappedby = "province", targetentity = town.class) @jsonmanagedreference("province-town") private list<town> towns; public long getid() { return id; } public void setid(long id) { this.id = id; } public string getname() { return name; } public void setname(string name) { this.name = name; } public list<town> gettowns() { return towns; } public void settowns(list<town> towns) { this.towns = towns; } }
child class
@entity @table(name = "town") public class town { @id @generatedvalue(strategy = generationtype.auto) @column(name = "town_id") private long id; private string name; @manytoone(cascade = cascadetype.merge) @joincolumn(name = "province_id") @jsonbackreference("province-town") private province province; private long kilometer; public long getid() { return id; } public void setid(long id) { this.id = id; } public string getname() { return name; } public void setname(string name) { this.name = name; } public province getprovince() { return province; } public void setprovince(province province) { this.province = province; } public long getkilometer() { return kilometer; } public void setkilometer(long kilometer) { this.kilometer = kilometer; } }
the response i'm getting this
{ "id" : 1, "name" : "some town", "kilometer" : 350 }
what i'm expecting is
{ "id" : 1, "name" : "some town", "province" : { //province data..... } "kilometer" : 350 }
i able show this, objects used not spring-data-jpa entities, simple pojos.
is there problem entities? or there else?
swap @jsonbackreference
, @jsonmanagedreference
. basically:
@jsonmanagedreference private province province; @jsonbackreference private list<town> towns;
Comments
Post a Comment