I'm working with the JPA API (Hibernate-backed), and have the following code:
public List<?> getGenericListing(Class<?> clazz) {
//Other logic comes before...
Query qry = entityManager.createNativeQuery(sql, clazz);
return qry.getResultList(); //Returns an untyped list, part of JPA spec
}
public List<SpecificObject> getSpecificListing() {
return (List<SpecificObject>) getGenericListing(SpecificObject.class);
}
Is there a better way to return the List<?> other than type-casting it against the List of SpecificObject?
You can put the cast into getGenericListing:
public <T> List<T> getGenericListing(Class<T> clazz) {
//Other logic comes before...
Query qry = entityManager.createNativeQuery(sql, clazz);
return (List<T>) qry.getResultList(); //Returns an untyped list, part of JPA spec
}
what's the nature of your sql? If dynamic queries feature isn't necessary to you then you can use this solution:
public <T> List<T> getGenericListing(Class<T> clazz) {
//Other logic comes before...
TypedQuery<T> qry = entityManager.createNamedQuery(sql, clazz);
return qry.getResultList();
}
where 'sql' is a name of NamedNativeQuery, for example declared as
@NamedNativeQuery(
name="sql_name",
query="SELECT * " +
"FROM foo_table t " +
"WHERE t.foo_field = ? ",
resultClass=fooEntityClass.class
)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With