【问题标题】:Unable to cast the resultant of the query into desired object in hibernate无法将查询的结果转换为休眠中的所需对象
【发布时间】:2015-07-28 13:34:20
【问题描述】:

我无法将查询结果转换为所需对象 UserTransactionInADay

这是我的实现

    @Override
            public UserTransactionInADay getTodaysActivity() {
                Date date = new Date();
                String modifiedDate= new SimpleDateFormat("yyyy-MM-dd").format(date);
                Session session = getSession();
                session.clear();
                @SuppressWarnings("unchecked")
                Query qry = session
                .createQuery(
                                "Select u.infoDate, sum(u.totalActiveUsers) as totalActiveUsers, sum(u.plotsVisited) as plotsVisited, sum(u.totalDataSet) as totalDataSet, sum(u.totalAlerts) as totalAlerts, sum(u.totalCropStages) as 

totalCropStages, sum(u.activitiesClosed) as activitiesClosed, sum(u.totalPlotInput) as totalPlotInput, sum(u.totalHarvest) as totalHarvest from UserTransactionInADay u where u.infoDate = ? group by u.infoDate");
            qry.setString(0, modifiedDate);
            List<UserTransactionInADay> userTransactionInADay = qry.list();
            return userTransactionInADay.get(0);
        }

我这样抛出的错误

java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to com.raghu.model.UserTransactionInADay
    com.raghu.dao.CropinDaoImpl.getTodaysActivity(CropinDaoImpl.java:92)
    com.raghu.service.CropinServiceImpl.getTodaysActivity(CropinServiceImpl.java:68)
    sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)

【问题讨论】:

    标签: sql spring hibernate spring-mvc


    【解决方案1】:

    我认为您需要稍微回顾一下Hibernate docs。您正在选择一堆数据并尝试将其转换为实体(我假设)集合。

    您的查询将返回一个 Object[][]。

    假设您的 UserTransactionInADay 具有适当的构造函数,您需要执行以下操作:

    "SELECT NEW UserTransactionInADay(u.infoDate, sum(u.totalActiveUsers) 
        AS totalActiveUsers, SUM(u.plotsVisited) AS plotsVisited,
        SUM(u.totalDataSet) AS totalDataSet, SUM(u.totalAlerts) AS totalAlerts,
        SUM(u.totalCropStages) AS totalCropStages, SUM(u.activitiesClosed) AS activitiesClosed,
        SUM(u.totalPlotInput) AS totalPlotInput, SUM(u.totalHarvest) AS totalHarvest) 
    FROM UserTransactionInADay u WHERE u.infoDate = ? GROUP BY u.infoDate"
    

    这将再次返回 UserTransactionInADay 对象,假设该类型有适当的构造函数。

    【讨论】:

      猜你喜欢
      • 2012-03-20
      • 1970-01-01
      • 2013-08-13
      • 1970-01-01
      • 2019-12-29
      • 1970-01-01
      • 2012-03-09
      • 1970-01-01
      • 2012-10-18
      相关资源
      最近更新 更多