JPQL
Query the object model, and know when a string is no longer enough.
JPQL and Criteria API
entityManager.find() covers only one need: retrieving an entity whose identifier you already know. Everything else (searching, filtering, sorting, aggregating, joining) goes through a query. JPA offers two forms, and choosing between them is not a matter of taste.
JPQL is a text-based language that looks like SQL but is not SQL. The difference is fundamental and fits in one sentence: JPQL queries the object model, not the schema. You write select l from Livre l where l.auteur.nom = :nom, and Hibernate decides that a join on auteur is needed, with which alias, in which dialect. Rename a column in the mapping and the query remains valid, because it never mentioned columns.
The downside is that a JPQL query is a string: the compiler does not check it. A typo in an attribute name only shows up at runtime. If the query is named, it shows up at application startup, which is already better. The Criteria API addresses exactly this problem by building the query through method calls that are checked at compile time.
This chapter is also where the N+1 query problem stops being inevitable, because it is in the query, and nowhere else, that you declare what you need. The DTO projections that end this lesson are the cleanest answer: they fetch only the useful columns, and what they return contains no proxy that could issue a query later.
Comments
Comments are powered by GitHub Discussions
Sign in with GitHub to join the discussion