Skip to content

Instantly share code, notes, and snippets.

@Tonel
Created October 29, 2022 09:04
Show Gist options
  • Save Tonel/4e408b2063b09e8af15d25c6e4a240b5 to your computer and use it in GitHub Desktop.
Save Tonel/4e408b2063b09e8af15d25c6e4a240b5 to your computer and use it in GitHub Desktop.
// initializing the CriteriaBuilder and CriteriaQuery object
CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder();
// if you want to perform a multiselect() you need define
// a CriteriaQuery with the Tuple type
CriteriaQuery<Tuple> criteriaQuery = criteriaBuilder.createQuery(Tuple.class);
Root<Book> root = criteriaQuery.from(Book.class);
// defining the JOIN clauses
Join<Book, Author> author = root.join("authors");
Join<Book, Genre> genre = root.join("genres");
// defining the multi SELECT clause and
// specifying the WHERE conditions
criteriaQuery
.multiselect(root, genre)
.where(
criteriaBuilder.equal(author.get("id"), 3),
criteriaBuilder.equal(genre.get("id"), 5)
);
// retrieving the list of <Book, Genre> tuples
List<Tuple> bookGenreTuples = entityManager
.createQuery(criteriaQuery)
.getResultList();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment