Skip to content

Commit

Permalink
add a very nice criteria example to Intro doc
Browse files Browse the repository at this point in the history
  • Loading branch information
gavinking committed May 27, 2023
1 parent fab058a commit 406b039
Showing 1 changed file with 24 additions and 1 deletion.
25 changes: 24 additions & 1 deletion documentation/src/main/asciidoc/introduction/Interacting.adoc
Original file line number Diff line number Diff line change
Expand Up @@ -690,7 +690,7 @@ We're ready to create a criteria query.
----
CriteriaQuery<Book> query = cb.createQuery(Book.class);
Root<Book> 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));
}
Expand Down Expand Up @@ -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

Expand Down

0 comments on commit 406b039

Please sign in to comment.