I am working on a spring boot project with postgress. I am facing an issue while parsing jpa native query (with table join) result list into JSONObject
I have two tables
create table person
(
id serial primary key,
name varchar(50)
);
create table contacts
(
id serial primary key,
person_id int,
key varchar(50),
value varchar(100),
foreign key (person_id) references person (id)
);
Sample data in the table
insert into person values (1, 'A');
insert into person values (2, 'B');
insert into contacts values (1, 1, 'EMAIL', 'a@b.com');
insert into contacts values (2, 1, 'PHONE', '123');
insert into contacts values (3, 2, 'EMAIL', 'b@b.com');
insert into contacts values (4, 2, 'PHONE', '456');
Spring boot code to fetch the data by using native query.
String query = "select p.id, p.name, c.key, c.value from person p LEFT JOIN contacts c on p.id = c.person_id";
Query nativeQuery = entityManager.createNativeQuery(query);
List<Object[]> resultList = nativeQuery.getResultList();
I would like to get the output as a list of JSONObject
[{
"id": 1,
"name": "A",
"contacts": [{
"key": "EMAIL",
"value": "a@b.com"
},
{
"key": "PHONE",
"value": "123"
}
]
},
{
"id": 2,
"name": "B",
"contacts": [{
"key": "EMAIL",
"value": "b@b.com"
},
{
"key": "PHONE",
"value": "456"
}
]
}
]
OR the result should be directly into POJO
List<Person> resultList = nativeQuery.getResultList();
in this case, I have a person class and contacts class with @OneToMany annotation.