我有List propertyIds。我想通过Collections获得propertyIds。这是我的代码:
Collection<Long> propertyIds = externalTaxManager.getPropertyIdsByTaxId(id); //Return type must be Collection<Long>
这是我的DAOImpl,
public Collection<Long> getPropertyIdsByTaxId(Long externalTaxId) {
SQLQuery query = currentSession().createSQLQuery("select b.OMH_PROPERTY_ID from OMH_EXTERNAL_TAX a , " +
"OMH_EXTERNAL_TAX_PROP_XREF b\n" +
"where a.OMH_EXTERNAL_TAX_ID=b.OMH_EXTERNAL_TAX_ID and a.OMH_EXTERNAL_TAX_ID = :externalTaxId ")
.addScalar("OMH_PROPERTY_ID" , LongType.INSTANCE);
query.setParameter("externalTaxId", externalTaxId);
Collection<BigDecimal> propertyIdsList = (Collection<BigDecimal>) query.list();
Long val = null;
Collection<Long> expRes = new HashSet<Long>();
for(BigDecimal values : propertyIdsList){
val = values.longValue();
expRes.add(val);
}
return expRes;
}
以上查询在与externalTaxId关联时返回500+个值。
抛出的异常是:
java.lang.ClassCastException: java.math.BigDecimal cannot be cast to java.lang.Long.
怎么了?
答案 0 :(得分:2)
查看您的预期回报类型:
Collection<Long>
但是DB返回:
Collection<BigDecimal>
所以,您应该将代码更改为:
Collection<BigDecimal> propertyIdsList = query.list();
然后尝试以其他方式将BigDecimal强制转换为Long;
^ _ ^原谅我可怜的英语..
答案 1 :(得分:0)
以下片段按预期为我工作。
public Collection<Long> getPropertyIdsByTaxId(Long externalTaxId) {
SQLQuery query = currentSession().createSQLQuery("select b.OMH_PROPERTY_ID from OMH_EXTERNAL_TAX a , " +
"OMH_EXTERNAL_TAX_PROP_XREF b\n" +
"where a.OMH_EXTERNAL_TAX_ID=b.OMH_EXTERNAL_TAX_ID and a.OMH_EXTERNAL_TAX_ID = :externalTaxId ")
.addScalar("OMH_PROPERTY_ID", LongType.INSTANCE);
query.setParameter("externalTaxId", externalTaxId);
Collection<BigDecimal> propertyIdsList = (Collection<BigDecimal>) query.list();
Long propertyIdsListValue = null;
Collection<Long> propertyIds = new HashSet<Long>();
for (BigDecimal propertyId : propertyIdsList) {
propertyIdsListValue = propertyId.longValue();
propertyIds.add(propertyIdsListValue);
}
return propertyIds;
}