yogesh
yogesh

Reputation: 11

Exception when getting Collection<Long> values using Hibernate - ClassCastException: java.math.BigDecimal cannot be cast to java.lang.Long

I've got List propertyIds. And I want to get propertyIds by Collections. This is my code:

Collection<Long> propertyIds = externalTaxManager.getPropertyIdsByTaxId(id);  //Return type must be Collection<Long>

This is my 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;
}

above Query returns 500+ values in associating with externalTaxId.

Exception thrown is :

java.lang.ClassCastException: java.math.BigDecimal cannot be cast to java.lang.Long.

What's wrong ?

Upvotes: 0

Views: 1027

Answers (2)

yogesh
yogesh

Reputation: 11

Following snippet worked for me as expected.

   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;
    }

Upvotes: 0

star
star

Reputation: 331

look at your expected return type:

Collection<Long>

but the DB returns :

Collection<BigDecimal>

so ,you should change your code to:

Collection<BigDecimal> propertyIdsList =  query.list();

then try to cast BigDecimal to Long in other way;

^_^ forgive my poor English..

Upvotes: 2

Related Questions