I have a project in which I have multiple POJO classes.These classes are mapped with database using Hibernate.I want to return data from database in JSON.My code is:
@RequestMapping(value="{userid}",method=RequestMethod.GET)
public @ResponseBody List<IterationInfo> getIterationInfoInJSON(@PathVariable int userid)
{
Configuration con = new Configuration();
con.configure("hibernate.cfg.xml");
SessionFactory SF = con.buildSessionFactory();
Session session= SF.openSession();
Transaction TR = session.beginTransaction();
Query query=session.createQuery("from IterationInfo");
List<IterationInfo> listiterationinfo=query.list();
session.close();
SF.close();
return listiterationinfo;
}
IterationInfo is a POJO class.List has the data from the query.But I want data from multiple Tables/POJO classes as a single JSON.I am able to return data from IterationInfo table.But how to return from multiple tables/POJO classes.
Create a wrapper dto containg all the data you need, for example:
class SomeResponseDto {
private List<IterationInfo> iterationInfo;
private List<AnotherPojoClass> anotherPojoClasses;
// getters, setters
}
And now you can combine your data into single JSON object:
@RequestMapping(value="{userid}",method=RequestMethod.GET)
public @ResponseBody SomeResponseDto getIterationInfoInJSON(@PathVariable int userid) {
// code
SomeResponseDto dto = new SomeResponseDto();
dto.setIterationInfos(listiterationinfo);
dto.setAnotherPojoClasses(anotherPojoClasses);
return dto;
}
Class A{ //POJO Class 1
private String id;
private String name;
//Getter and setter methods
}
Class B{ //POJO Class 2
private String id;
private String name;
//Getter and setter methods
}
Create object for the POJO classes.
@RequestMapping(value="{userid}",method=RequestMethod.GET)
public @ResponseBody List<Object> getIterationInfoInJSON(@PathVariable int userid)
{
A a=new A(); B b=new B();
List<Object> ls=new List<Object>();
ls.add(a);
ls.add(b);
return ls;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.