How to avoid child of child objects in Spring JPA?

*爱你&永不变心* 提交于 2020-01-16 18:18:13

问题


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;
    }
}


来源:https://stackoverflow.com/questions/51618138/how-to-avoid-child-of-child-objects-in-spring-jpa

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!