Rakosi Rakosi - 1 year ago 78
Java Question

Why do I need to put @NamedQuery on Entity class?

I am currently learning about JPA NamedQueries and tried to use it in GuestServlet:

Query getGuests = em.createNamedQuery("myq");
List<Guest> guests = getGuests.getResultList();

It works when I put the @NamedQuery in Entity class:

query = "SELECT g FROM Guest g")
public class Guest {

But when I try to use it in Servlet as following:

query = "SELECT g FROM Guest g")
public class GuestServlet extends HttpServlet {...}

I get the following error:

java.lang.IllegalArgumentException: No query defined for that name [myq]

Why am I forced to put @NamedQuery in Entity class while I use it in Servlet ?

Answer Source

The GuestServlet is not managed by your jpa provider. Hibernate (or whatever) simply isn't aware of the named query.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download