Named and Native Queries in JPA :-
Named
queires are reusable and can be declared at Entity level
@NamedQuery
annotation is used
multiple
named queries are declared in @NamedQueries
For
executing native queries we use @NamedNativeQueries
@NamedQuery
:-
@NamedQuery(name
= "allCompanyDetails",
query = "SELECT c FROM Company c")
Named
query is called by using query =
em.createNamedQuery("allCompanyDetails");
@NamedQueries
:- annotation is used for declaring
multiple named queries at entity level
In
the below snippet we have two named queries-"allCompanyDetails"
and "onlyMailIds"
@NamedQueries({
@NamedQuery(name
= "allCompanyDetails",
query = "SELECT c FROM Company c"),
@NamedQuery(name="onlyMailIds",query="SELECT
c.mail FROM Company c")
})
Native
Queries are used to execute SQL statements directly and to call
procedures and functions from JPA
@NamedNativeQueries
:-
@NamedNativeQuery(name
= "nativeQueryEx",
query = "select * from company")
entityManager.createNativeQuery("query")
is used to execute native queries
Similar
to SQL in JPQL we can write join queries etc,instead of Table names
we use Entity class names
Query
query = em.createQuery("SELECT c
from Company c,Department d where c.mail= d.mail and c.name LIKE
'T%'");