How to get the maximum number of cases from an offset value using EntityManager in Spring JPA

How to get the maximum number of cases from an offset value using EntityManager in Spring JPA

This method is used to retrieve the maximum number of results from the offset value (initial value = 0).

The offset value is set in the argument of the setFirstResult method. 0 is used as the base value and the first result is retrieved.

The argument of setMaxResults specifies the number of results (from the offset value) to be retrieved in a single SQL session.

Finally, the getResultList method executes the SQL and stores it in memory.

  @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

コメント

Discover more from 株式会社CONFRAGE ITソリューション事業部

Subscribe now to keep reading and get access to the full archive.

Continue reading

Copied title and URL