Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cleaner solution to returning generic objects (e.g. Lists) in Java

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?

like image 509
Jensen Ching Avatar asked Apr 10 '26 08:04

Jensen Ching


2 Answers

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
}
like image 148
Flavio Avatar answered Apr 12 '26 20:04

Flavio


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 
) 
like image 32
callfarc0de Avatar answered Apr 12 '26 22:04

callfarc0de



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!