What is a named query?

Let me guess: you’ve stumbled upon concept of named queries and you wonder where it fits in SQL.

Well, from my knowledge, named queries haven’t got anything to do with “pure” SQL, but they’re a concept found in various ORM (object relational mapping) frameworks, ala Java Persistence API.

Basically, a named query is one way to map a name to a query that might be called several times in your code at different places.

So, instead of using

"SELECT i FROM Item i WHERE i.product.categoryID LIKE :cID"

as a string at various places in your code, you use this:

@NamedQuery( 
  name="MyEntity.getItemsPerProductCategory", 
  query="SELECT i FROM Item i WHERE i.product.categoryID LIKE :cID"
)

and afterwards you refer to this query using MyEntity.getItemsPerProductCategory.

Example taken from this site.

You might wonder why this is useful?

A JPA implementation like Hibernate can check validity for named queries at startup, so in one way, you’ve got safe type checking. This will help reduce errors at runtime.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)