Hi to all i'm new in J2EE world.
I'm trying to use @Namequery to get a List of String from my model(the class is called Element), in this case the attribute name.
Why when I use @NamedQuery(name="Element.findAllNames",query="SELECT e.name FROM Element e")
and I use it on my ElementMgrBean using:
public List<String> getAllElementsName() {
return em.createNamedQuery(Element.FIND_ALLNAMES,Element.class).getResultList();
}
the result appears to be a list of elements instead of a list of String as I expected.
Someone can explain me why Java says: "Type mismatch: cannot convert from List of Element to List of String"??
PS: I have defined:public static final String FIND_ALLNAMES = "Element.findAllNames";
When you write em.createNamedQuery("NameOfNamedQuery", MyClass.class)
, you say you want to fetch MyClass instances (in your query MyClass==Element). The problem is now, that your query SELECT e.name FROM Element e
returns Strings instead of Element instances (as the e.name fields are of type Strings).
In order to correct the problem you either correct the call to em.createNamedQuery(Element.FIND_ALLNAMES, String.class)
(the preferred solution, as it returns a TypedQuery<String>
instance), or you remove the second parameter: em.createNamedQuery(Element.FIND_ALLNAMES)
(in this case you are not type-safe anymore, as it returns a Query
instance).