I’m trying to use the following NamedQuery in my entity class BrandMstr.
@NamedQuery(name = "BrandMstr.findAllBrands", query = "SELECT * FROM BrandMstr")
It throws an exception javax.ejb.EJBException with a long stack trace indicating that unexpected token [*] found.
The same query when I use in native query it works with no problem as follows.
Collection<BrandMstr>brands=(Collection<BrandMstr>)
em.createNativeQuery("SELECT * FROM BrandMstr",BrandMstr.class).getResultList());
Where em is the EntityManager object annotated with a specific PersistanceContext as follows
@PersistenceContext(unitName="OnlineShoppingCartSystem-ejbPU")
EntityManager em=null;
Why is the meta character * not allowed in NamedQuery while the same can be used in NativeQuery? also, we can perform all most all operations using NamedQuery, then why NativeQuery? In which particular situation, NativeQuery should be used?
From the Java EE 6 documentation of
@NamedQuery:Your query is a native query instead.
You should change it to a JPQL-query, something like:
Regarding your second question:
Use native queries for the operations that are database vendor specific and cannot be done with JPQL.