如何解决如何在Hibernate JPA中限制获取查询的大小?
我收到此错误com.mysql.jdbc.PacketTooBigException,并在代码中进行了跟踪,看来它出现在以下情况下(但仅在测试中发生)
public interface Students extends JpaRepository<Student,Integer> {
@EntityGraph("Student.withProgramAndSchedule")
@Query("from Student s")
Iterable<Student> findAllWithProgramAndSchedule();
}
@Entity
@NamedEntityGraph(
name = "Student.withProgramAndSchedule",attributeNodes = {
@NamedAttributeNode("programEnrollments"),@NamedAttributeNode("schedules")
}
)
public class Student implements Serializable {
...
}
仅在DataJpaTest期间,即使我已经清除了实体管理器,它似乎也无法清理实体管理器上下文
@After
public void clearEntityManager() {
entityManager.clear();
}
由于这是匿名的真实数据,因此它具有成千上万的记录,发生的事情是创建了一个看起来像
的查询select ... from ... where studentSchedule_0.id in (?,?,... thousands of ? later,... ?)
然后,它超出了1MB的数据包限制。
所以我的问题是(因为我无法在参考文献中找到它)在进行ID提取时是否可以限制查询的大小?
解决方法
您可以使用jpa分页来限制查询结果:
Iterable<Student> findAllWithProgramAndSchedule(Pageable pageable);
并进行测试:
Pageable page= PageRequest.of(1,5);
,
我不在一个让我编写代码以确认我认为会起作用的地方。
使用findFirst如下:
findFirstWithProgramAndSchedule()//获得一个
或者限制为前10个
findFirst10WithProgramAndSchedule()
尽管我今天无法编写代码,但我仍在努力提供帮助。因此,我等着看其他人是否有答案,但是我相信这对于参考文献是可行的。
参考:
Technical differences between Spring Data JPA's findFirst and findTop
https://docs.spring.io/spring-data/jpa/docs/current/reference/html/#repositories.limit-query-result
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。