不可能有标准的联合邮局。 Hibernate 提供所有权方法setPara amountList(>
,但只与Hibernate Session合作,在JPA的 EntityManager
中没有。
I came up with the following workaround for Hibernate, which is not ideal but almost standard JPA code and has some nice properties to it.
对于开户人来说,你可以在<条码>上保存被点名的原住地。 档案:
<named-native-query name="Item.FIND_BY_COLORS" result-class="com.example.Item">
<query>
SELECT i.*
FROM item i
WHERE i.color IN ( blue , :colors )
AND i.shape = :shape
</query>
</named-native-query>
The placeholder is wrapped in single quotes, so it s a valid native JPA query. It runs without setting a parameter list and would still return correct results when other matching color parameters are set around it.
Set the parameter list in your DAO or repository class:
@SuppressWarnings("unchecked")
public List<Item> findByColors(List<String> colors) {
String sql = getQueryString(Item.FIND_BY_COLORS, Item.class);
sql = setParameterList(sql, "colors", colors);
return entityManager
.createNativeQuery(sql, Item.class)
.setParameter("shape", BOX )
.getResultList();
}
No manual construction of query strings. You can set any other parameter as you normally would.
Helper methods:
String setParameterList(String sql, String name, Collection<String> values) {
return sql.replaceFirst(":" + name, String.join(" , ", values));
}
String getQueryString(String queryName, Class<?> resultClass) {
return entityManager
.createNamedQuery(queryName, resultClass)
.unwrap(org.hibernate.query.Query.class) // Provider specific
.getQueryString();
}
因此,我们基本上重新阅读了从orm.xml
上显示的问询,人工设定了参数清单,然后建立了原住的JPA询问。 不幸的是,createNative Query (.getResultList (>
>>回到了一种未分类的盘问和没有分类的清单,尽管我们通过了一个结果类别。 因此,@SuppressWarnings ("unchecked”)
。
Downside: Unwrapping a query without executing it may be more complicated or impossible for JPA providers other than Hibernate. For example, the following might work for EclipseLink (untested, taken from Can I get the SQL string from a JPA query object?):
Session session = em.unwrap(JpaEntityManager.class).getActiveSession();
DatabaseQuery databaseQuery = query.unwrap(EJBQueryImpl.class).getDatabaseQuery();
databaseQuery.prepareCall(session, new DatabaseRecord());
Record r = databaseQuery.getTranslationRow();
String bound = databaseQuery.getTranslatedSQLString(session, r);
String sqlString = databaseQuery.getSQLString();
另一种办法是在文本档案中储存询问,并增加从那里读到的代码。