ClassCastException (String to Long) when running a subquery with Criteria
classcastexception, hibernate, hibernate-criteria, java, mysql
Solution
I'm pretty sure you'll find that the exception comes in fact from this line:
sellOrderSizeCriteria.add(Restrictions.eq("marketDataId", "md.id"));
This line tries to compare the `marketDataId` property of `MarketOrder` to the String `"md.id"`. That's not what you want to do. What you want to do is to compare the `marketDataId` property of `MarketOrder` to the `id` property of `md`. And you thus need to use eqProperty() instead:
sellOrderSizeCriteria.add(Restrictions.eqProperty("marketDataId", "md.id"));
Problem
First my setups : - mysql-connector-java 5.1.24 - hibernate-core 4.1.10.Final I've got an ClassCastException when running this criteria query : ``` Criteria sellableItemsCriteria = session.createCriteria(MarketData.class, "md"); sellableItemsCriteria.add(Restrictions.in("region", regions)); sellableItemsCriteria.add(Restrictions.in("itemTypeId", items)); DetachedCriteria sellOrderSizeCriteria = DetachedCriteria.forClass(MarketOrder.class); sellOrderSizeCriteria.add(Restrictions.eq("marketDataId", "md.id")); sellOrderSizeCriteria.add(Restrictions.eq("bid", false)); sellOrderSizeCriteria.setProjection(Projections.count("marketDataId")); sellableItemsCriteria.add(Subqueries.lt(0L, sellOrderSizeCriteria)); ``` The exception : ``` Caused by: java.lang.ClassCastException: java.lang.String cannot be cast to java.lang.Long ``` The problem is from this line (first i tried with 0 instead of 0L and i got Integer cannot be cast to Long so that why i switched to a Long) : ``` sellableItemsCriteria.add(Subqueries.lt(0L, sellOrderSizeCriteria)); ``` And this is the mysql query i want to run : ``` SELECT md.* FROM `marketdata` md WHERE md.region IN (:regions) AND md.item_typeID IN (:items) AND (SELECT COUNT(marketData_id) FROM `marketorder` WHERE marketData_id = md.id AND bid = 0) > 0 ``` How can i resolve the cast problem ? Or maybe there is a better way to do this with Criteria ? Thanks