heintzl / Kernbeisser-Gradle

the Kernbeisser Repository with Gradle Support
5 stars 1 forks source link

Replaced all queries with Criteria API #756

Closed julikiller98 closed 5 months ago

julikiller98 commented 5 months ago
public static Article nextArticleTo(
      EntityManager em, int suppliersItemNumber, Supplier supplier, PriceList excludedPriceList) {
    return em.createQuery(
            "select a from Article a where supplier = :s and priceList != :pl "
                + "order by abs(a.suppliersItemNumber - :sn) asc",
            Article.class)
        .setParameter("s", supplier)
        .setParameter("sn", suppliersItemNumber)
        .setParameter("pl", excludedPriceList)
        .setMaxResults(1)
        .getResultStream()
        .findAny()
        .orElse(null);
  }

Is now equal to:

  public static Article nextArticleTo(
      EntityManager em, int suppliersItemNumber, Supplier supplier, PriceList excludedPriceList) {
    return QueryBuilder.selectAll(Article.class)
        .where(ArticleField.supplier.eq(supplier), ArticleField.priceList.eq(excludedPriceList).not())
        .orderBy(diff(ArticleField.suppliersItemNumber, asExpression(suppliersItemNumber)).asc())
        .getResultStream(em)
        .findFirst()
        .orElse(null);
  }

ArticleField can be imported statically to remove boilerplate:

  import static kernbeisser.DBEntities.TypeFields.ArticleField.*;
  public static Article nextArticleTo(
      EntityManager em, int suppliersItemNumber, Supplier supplier, PriceList excludedPriceList) {
    return QueryBuilder.selectAll(Article.class)
        .where(supplier.eq(supplier), priceList.eq(excludedPriceList).not())
        .orderBy(diff(suppliersItemNumber, asExpression(suppliersItemNumber)).asc())
        .getResultStream(em)
        .findFirst()
        .orElse(null);
  }

Also there is support for simple operations like:

  HashSet<String> usernames =
        new HashSet<>(
            QueryBuilder.select(UserField.username)
                .where(UserField.firstName.eq(firstName))
                .getResultList());

Due to the UserField.username the Querybuilder knows that the tabel is User, and the returntype String so it creates a query returning a string result stream, making it faster and easier than to extract it first out of a tuple.