How to avoid child of child objects in Spring JPA?

2019-09-04 00:38发布

问题:

I am using Spring JPA. I have three entities Student, ClassRoom and School like below

@Entity
public class Student implements Serializable {
    private static final long serialVersionUID = 1L;

    @Id
    @Column(name="id")
    private int id;

    @Column(name="name")
    private String name;

    @Column(name="name")
    private int age;

    ...
}

@Entity
public class ClassRoom implements Serializable {
    private static final long serialVersionUID = 1L;

    @Id
    @Column(name="id")
    private int id;

    @Column(name="name")
    private String name;

    @OneToMany(fetch = FetchType.EAGER)
    @JoinColumn(name="id")
    private List<Student> students;

    ...
}

@Entity
public class School implements Serializable {
    private static final long serialVersionUID = 1L;

    @Id
    @Column(name="id")
    private int id;

    @Column(name="name")
    private String name;

    @OneToMany
    @JoinColumn(name="id")
    private List<ClassRoom> classRooms;

    ...
}

Now I am fetching School with ClassRoom details and I don't need Student details.

But Student entity in ClassRoom is set to Fetch Type EAGER. How can I get School records with ClassRoom records without Student records.

Note: I can't remove FetchType.EAGER on Student Entity.

回答1:

You'll have to create a custom Repository then create a method inside either through an implementation of that interface or make the method default. Here's an example of what those method(s) might look like (assuming you're going the implementation route):

public class SchoolRepositoryImpl implements SchoolRepository {

    @Autowired
    EntityManager em;

    public List<School> getSchoolById(Long schoolId) {
           Query q = em.createNativeQuery("select...");
           q.setParameter("schoolId", schoolId);
           List<Object[]> results = q.getResultAsList();
           return this.mapSchool(results);
    }

    private List<School> mapSchool(List<Object[]> entities){
            List<School> schools = new ArrayList<>();
            for(Object[] o : entities){
                  school s = new School();
                  s.set...
                  s.set...
                  schools.add(s);
            }
            return schools;
    }
}