From 406b039f509cd8f6ae610bb7c4765729474edd3b Mon Sep 17 00:00:00 2001 From: Gavin Date: Sun, 28 May 2023 01:40:56 +0200 Subject: [PATCH] add a very nice criteria example to Intro doc --- .../asciidoc/introduction/Interacting.adoc | 25 ++++++++++++++++++- 1 file changed, 24 insertions(+), 1 deletion(-) diff --git a/documentation/src/main/asciidoc/introduction/Interacting.adoc b/documentation/src/main/asciidoc/introduction/Interacting.adoc index 4f62e21893..463cd4399c 100644 --- a/documentation/src/main/asciidoc/introduction/Interacting.adoc +++ b/documentation/src/main/asciidoc/introduction/Interacting.adoc @@ -690,7 +690,7 @@ We're ready to create a criteria query. ---- CriteriaQuery query = cb.createQuery(Book.class); Root book = query.from(Book.class); -Predicate where = conjunction(); +Predicate where = cb.conjunction(); if (titlePattern != null) { where = cb.and(where, cb.like(book.get(Book_.title), titlePattern)); } @@ -885,6 +885,29 @@ But perhaps you find it more aesthetically pleasing. On the other hand, when we're passing query results around the system, the use of `select new` with a `record` type is much better than manually unpacking an `Object[]` array. +Now, the criteria query API offers a much more satisfying solution to the problem. +Consider the following code: + +[source,java] +---- +var cb = sessionFactory.getCriteriaBuilder(); +var query = cb.createQuery(Tuple.class); +var book = query.from(Book.class); +var bookTitle = book.get(Book_.title); +var bookIsbn = book.get(Book_.isbn); +var bookPrice = book.get(Book_.price); +query.select(cb.tuple(bookTitle, bookIsbn, bookPrice)); +var resultList = session.createSelectionQuery(query).getResultList(); +for (var result: resultList) { + String title = result.get(bookTitle); + String isbn = result.get(bookIsbn); + BigDecimal price = result.get(bookPrice); + ... +} +---- + +This code is manifestly completely typesafe, and much better than we can hope to do with HQL. + [[named-queries]] === Named queries