0

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.

4

1 回答 1

0

您必须创建一个自定义存储库,然后通过该接口的实现在内部创建一个方法或创建该方法default。以下是这些方法可能看起来的示例(假设您正在执行实现路线):

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;
    }
}
于 2018-07-31T17:40:48.240 回答