Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What exactly does type-safe queries means?

While going through JPA, QueryDSL they all have included the concept of type-safe queries. But what exactly is it? According to blogs/articles, I guess it is a feature of JPA/QueryDSL that validates their parameter type while making queries. And any thing wrong with the query would show up in compile time instead of run time. Am I right on this? Is it only for this or am I missing something here?

like image 700
Mani Rai Avatar asked Apr 04 '14 10:04

Mani Rai


2 Answers

QueryDSL and Criteria are libraries that try to enforce the data type validation when you assemble a query in JPA.

Just because JPQL is just a query that will be only verified on execution time, it's easy to write an invalid query that is not detected by the compiler. Of course, it's faster to fix things while you're coding than while you're running the app.

Of course, neither QueryDSL or Criteria can protect your query from all kinds of errors (data type related or not) but it's safer than JPQL.

On the other hand, writing queries in JPQL can be much easier and faster. Always the tradeoff :-)

like image 71
Leo Avatar answered Oct 05 '22 01:10

Leo


An API is type safe if it leverages the type system of the programming language to prevent type errors. Specifically, QueryDSL enables the compiler to verify that

  1. all classes used in a query exist (no typos ...) and are persistent (i.e. mapped to a database)
  2. all properties used in a query exist for that object, and are persistent
  3. the resulting query is syntactically valid (no missing clauses or keywords)
  4. all operators receive operands of an acceptable type

Moreover, the expressive query api enables your IDE to provide code completion (also for domain classes and their properties), and refactoring support (if a property is renamed, you can simply rename it in the metamodel, and the IDE will rename in all queries).

As a side benefit, it's very difficult to write a query containing an SQL injection vulnerability.

In short, using QueryDSL instead of JPQL (or JPA critieria queries in the absence of a static metamodel) makes writing or changing queries faster and less error prone.

like image 38
meriton Avatar answered Oct 04 '22 23:10

meriton