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

时间:2013-04-27 23:35:57

标签: java mysql hibernate classcastexception hibernate-criteria

首先我的设置:

  1. mysql-connector-java 5.1.24
  2. hibernate-core 4.1.10.Final
  3. 运行此条件查询时,我遇到了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做到这一点?

    由于

1 个答案:

答案 0 :(得分:11)

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

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

此行尝试将marketDataId的{​​{1}}属性与字符串MarketOrder进行比较。这不是你想要做的。您要做的是将"md.id"的{​​{1}}属性与marketDataId的{​​{1}}属性进行比较。因此,您需要使用eqProperty()代替:

MarketOrder