[英]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: 我正在使用JPA API(由Hibernate支持),并且具有以下代码:
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? 除了针对SpecificObject的列表进行类型转换之外,还有没有更好的方法来返回
List<?>
?
You can put the cast into getGenericListing
: 您可以将演员表放入
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? 你的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 其中“ sql”是NamedNativeQuery的名称,例如声明为
@NamedNativeQuery(
name="sql_name",
query="SELECT * " +
"FROM foo_table t " +
"WHERE t.foo_field = ? ",
resultClass=fooEntityClass.class
)
Here you don't need to cast the result, and namedQueryName is just the name of named query. 在这里,您不需要强制转换结果,namedQueryName只是命名查询的名称。
public <T> List<T> getGenericListing(final String namedQueryName,Class<T> clazz) {
TypedQuery<T> qry = em.createNamedQuery(namedQueryName, clazz);
return qry.getResultList();
}
Additionally I prefer using xml to store named queries rather than strings in java class - it's more maintainable, so my persistence.xml has: 另外,我更喜欢使用xml而不是Java类中的字符串来存储命名查询-它更易于维护,因此我的persistence.xml具有:
<mapping-file>META-INF/Finders.xml</mapping-file>
Following this approach you can change query without compiling project which I find helpful, excerpt from Finder.xml 按照这种方法,您可以在不编译项目的情况下更改查询,而我发现对项目没有帮助。
<named-query name="Country.findCountryByShortNameAndLocale">
<query>
SELECT c FROM Country c WHERE c.Country.shortName = :shortName AND c.language.locale = :locale
</query>
</named-query>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.