Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is a named query?

Tags:

sql

I have read its definition but not able to understand fully.

like image 503
aloksapru Avatar asked Dec 23 '10 08:12

aloksapru


People also ask

What is the use of named query?

A named query is a predefined query that you create and associate with a container-managed entity (see "Using Annotations"). At deployment time, OC4J stores named queries on the EntityManager . At run time, you can use the EntityManager to acquire, configure, and execute a named query.

What is named query JPA?

Named queries are one of the core concepts in JPA. They enable you to declare a query in your persistence layer and reference it in your business code. That makes it easy to reuse an existing query. It also enables you to separate the definition of your query from your business code.

What is named query and native query?

Native query refers to actual sql queries (referring to actual database objects). These queries are the sql statements which can be directly executed in database using a database client. Similar to how the constant is defined. NamedQuery is the way you define your query by giving it a name.


2 Answers

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.

like image 109
darioo Avatar answered Oct 02 '22 16:10

darioo


I believe you are talking about Hibernate.

In simple terms, a named query is a query that can be identified by a name. You could define a named query as below and use it by its name.

@NamedQuery name="findAllUsers" query="SELECT u FROM Users u" findByNamedQuery("findAllUsers") 

You have more options and can pass in parameters to it as well.

like image 28
Jinesh Parekh Avatar answered Oct 02 '22 16:10

Jinesh Parekh