Rakosi Rakosi - 1 month ago 8
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");
@SuppressWarnings("unchecked")
List<Guest> guests = getGuests.getResultList();


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

@Entity
@NamedQuery(
name="myq",
query = "SELECT g FROM Guest g")
public class Guest {
...
}


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

@WebServlet({"/GuestServlet","/guest"})
@NamedQuery(
name="myq",
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

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