java – 使用Criteria运行子查询时ClassCastException(String to Long)

首先是我的设置:

> mysql-connector-java 5.1.24
> hibernate-core 4.1.10.Final

运行此条件查询时,我遇到了ClassCastException:

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

例外:

Caused by: java.lang.ClassCastException: java.lang.String cannot be cast to java.lang.Long

问题来自这一行(首先我尝试使用0而不是0L而且我得到的Integer不能转换为Long以便为什么我切换到Long):

sellableItemsCriteria.add(Subqueries.lt(0L, sellOrderSizeCriteria));

这是我想运行的mysql查询:

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

我该如何解决演员问题?

或者也许有更好的方法来使用Criteria?

谢谢

最佳答案
我很确定你会发现异常来自这一行:

sellOrderSizeCriteria.add(Restrictions.eq("marketDataId", "md.id"));

此行尝试将MarketOrder的marketDataId属性与字符串“md.id”进行比较.这不是你想要做的.你想要做的是将MarketOrder的marketDataId属性与md的id属性进行比较.因此,您需要使用eqProperty()

sellOrderSizeCriteria.add(Restrictions.eqProperty("marketDataId", "md.id"));

转载注明原文:java – 使用Criteria运行子查询时ClassCastException(String to Long) - 代码日志