一些背景信息:我有一个带有 Hibernate 的 Spring 应用程序。
我想要获取按 ID 过滤的所有位置实体,因此我将一组 ID 作为参数传递给查询。问题是在 query.setParameter("ids", locationIds);
行上出现以下错误:
:Parameter value element [728331] did not match expected type [java.lang.Long (n/a)]
我很困惑,因为我给出的集合是长整型值的集合。所以我认为在将其作为参数传递时不应该进行显式转换,对吗?有人建议是什么导致了错误吗?
我检查了其他类似的问题,但没有找到能解决我的问题的问题。
@Repository
@Transactional(propagation = Propagation.MANDATORY)
public class LocationDao {
@PersistenceContext
private EntityManager em;
public List<Location> getLocationsByIds(Set<Long> locationIds) {
if (locationIds == null || locationIds.isEmpty()) {
return null;
}
final TypedQuery<Location> query =
em.createQuery("FROM Location l WHERE l.id IN :ids", Location.class);
query.setParameter("ids", locationIds);
return query.getResultList();
}
}
@Entity
@Table(name = "location")
public class Location {
@Id
private Long id;
// other fields
}
编辑:Hibernate 实体管理器版本:4.3.8.Final
最佳答案
发现问题了。 locationIds
不完全是Set<Long> locationIds
但是Set<BigInteger>
.
我通过 native 查询检索 ID,因为我需要在位置中执行递归搜索。虽然我把它转换到 List<Long>
它实际上返回一个 List<BigInteger>
。这是代码:
private static final String SQL_FIND_LOCATION_AND_CHILDREN_IDS =
" WITH RECURSIVE result_table(id) AS ( "
+ " SELECT pl.id "
+ " FROM location AS pl "
+ " WHERE pl.id = :parentId "
+ "UNION ALL "
+ " SELECT c.id "
+ " FROM result_table AS p, location AS c "
+ " WHERE c.parent = p.id "
+ ") "
+ "SELECT n.id FROM result_table AS n";
@SuppressWarnings("unchecked")
public List<Long> getLocationAndAllChildren(Long parentId) {
final Query query = em.createNativeQuery(SQL_FIND_LOCATION_AND_CHILDREN_IDS);
query.setParameter("parentId", parentId);
return query.getResultList();
}
然后我可以直接获取 BigInteger 的 long 值,因为我确信这些值适合 Long 的大小。
@SuppressWarnings("unchecked")
public List<Long> getLocationAndAllChildren(Long parentId) {
final Query query = em.createNativeQuery(SQL_FIND_LOCATION_AND_CHILDREN_IDS);
query.setParameter("parentId", parentId);
final List<BigInteger> resultList = query.getResultList();
final List<Long> result = new ArrayList<Long>();
for (BigInteger bigIntId : resultList) {
result.add(bigIntId.longValue());
}
return result;
}
感谢大家的回复,很抱歉浪费了您的时间。
关于java - JPQL 集合参数 - 与预期类型不匹配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31158782/