Spring JPAでEntityManagerを使用してオフセット値からの最大件数を取得する方法

Spring JPAでEntityManagerを使用してオフセット値からの最大件数を取得する方法

オフセット値(初期値=0)から最大件数までを取得する方法です。

setFirstResultメソッドの引数でオフセット値を設定します。0を基底値として1件目から取得していきます。

setMaxResultsの引数で一回のSQLで取得する件数(オフセット値からの)を指定します。

最後にgetResultListメソッドでSQL実行しメモリに保持します。

  @RequestMapping(path = "/test/{offset}", method = RequestMethod.GET)
  public ResponseEntity test(@PathVariable Integer offset) {
    CriteriaBuilder builder = entityManager.getCriteriaBuilder();
    CriteriaQuery criteriaQuery = builder.createQuery(Employee.class);
    Root q = criteriaQuery.from(Employee.class);
    criteriaQuery.select(q);
    TypedQuery query = entityManager.createQuery(criteriaQuery);

    List employee = query.setFirstResult(offset).setMaxResults(1000).getResultList();
    int currentOffset = employee.size();

    employee.stream().forEach(e -> log.info("{}", e));

    return ResponseEntity.ok(Map.of("result", currentOffset));
  }
// curl -X GET http://localhost:8080/test/0

コメント

株式会社CONFRAGE ITソリューション事業部をもっと見る

今すぐ購読し、続きを読んで、すべてのアーカイブにアクセスしましょう。

続きを読む

タイトルとURLをコピーしました