简体   繁体   中英

get response with specific fields from entityManager.createQuery() join result in springboot API

I am using springboot with JPA to create REST APIs. I want to get all details from student and matching rows from address if present.

Below is my serviceImplementation

 EntityManager entityManager = entityManagerFactory.createEntityManager();
 query = entityManager.createQuery("select s , a  from Student s " +
                                         " left join Address a  " +
                                         " on s.id = a.student ")
       
        @SuppressWarnings("unchecked")
       List<Object> list = query.getResultList();

below is my Student Entity

@Entity
class Student{
private int id,
private String name,

 @ManyToOne(optional = false)
 @NotNull
 @JsonIgnoreProperties(value = "student", allowSetters = true)
 private User user; // User another entity
  --- getter and setter --
}

below is my Address Entity

class Address{
private int id;
private String addressLine;

 @ManyToOne(optional = true)
 @JsonIgnoreProperties(value = "address", allowSetters = true)
 private Student student; 
   --- getter and setter --
}

So it will return the all matching rows with relationship attributes like below

[{
 id :1,
 name: "qwert",
 user:{
   id: 1,
   createdBy:1
   createdOn:2021-08-21
}
}
{
 id: 1,
 addressLine:"kkkkk",
 student{
 id :1,
 name: "qwert",
 user{
   id: 1,
   createdBy:1
   createdOn:2021-08-21
}}}]

**I want output be like below**

[
{
 id :1,
     name: "qwert",
     user:{
       id: 1
}},
{
     id: 1,
     addressLine:"kkkkk"
}]

How we can achieve this? I tried with using POJO but could not achieve. I am beginner to Springboot and JPA. Can there is another way to get data from unrelated entites and return POJO with specific fields.

This should work:

List<Object[]> list = query.getResultList();
for (Object[] element: list) {
   Student s = element[0|;
   Address a = element[1];
   //.... do whatever necessary to save result to dto list
}

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM