Spring JPA中如何避免子对象的子对象?

时间:2018-07-31 16:33:45

标签: jpa spring-data-jpa jpa-2.0 hibernate-jpa

我正在使用Spring JPA。 我有如下三个实体Student,ClassRoom和School

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

    ...
}

现在,我要获取具有 ClassRoom 详细信息的学校,并且我不需要学生详细信息。

但是ClassRoom中的Student实体设置为Fetch Type EAGER。如何获得带有ClassRoom记录但没有Student记录的School记录。

注意:我无法删除学生实体上的FetchType.EAGER。

1 个答案:

答案 0 :(得分: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;
    }
}