Spring Data JPA - 模拟现有集合的“创建 + 连接”查询

Ozi*_*ile 5 java hibernate jpa spring-data spring-data-jpa

假设我有一个实体列表:

List<SomeEntity> myEntities = new ArrayList<>();
Run Code Online (Sandbox Code Playgroud)

SomeEntity.java:

@Entity
@Table(name = "entity_table")
public class SomeEntity{

@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private long id;
private int score;

public SomeEntity() {}

public SomeEntity(long id, int score) {
    this.id = id;
    this.score = score;
}
Run Code Online (Sandbox Code Playgroud)

MyEntityRepository.java:

@Repository
public interface MyEntityRepository extends JpaRepository<SomeEntity, Long> {

List<SomeEntity> findAllByScoreGreaterThan(int Score);
}
Run Code Online (Sandbox Code Playgroud)

所以当我运行时:

myEntityRepository.findAllByScoreGreaterThan(10);
Run Code Online (Sandbox Code Playgroud)

然后 Hibernate 会将表中的所有记录加载到我的内存中。有数百万条记录,所以我不想那样做。然后,为了相交,我需要将结果集中的每条记录与我的列表进行比较。在本机 MySQL 中,我在这种情况下会做的是:

  1. 创建一个临时表并将列表中的实体 ID 插入其中。
  2. 将这个临时表与“entity_table”连接起来,使用分数过滤器,然后只提取与我相关的实体(首先出现在列表中的实体)。

通过这种方式,我获得了很大的性能提升,避免了任何 OutOfMemoryErrors 并让数据库机器完成大部分工作。

有没有办法使用 Spring Data JPA 的查询方法(使用 hibernate 作为 JPA 提供程序)来实现这样的结果?我在文档或 SO 中找不到任何此类用例。

Mat*_*ldi 1

你可以:

1)通过JPA进行分页本机查询(记得添加order子句)并处理固定数量的记录

2)使用StatelessSession(参见文档