无法将查询结果强制转换为hibernate中的所需对象

时间:2015-07-28 13:34:20

标签: sql spring hibernate spring-mvc

我无法将查询结果强制转换为所需对象 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)

1 个答案:

答案 0 :(得分:0)

我认为您需要稍微检查一下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对象,假设该类型有适当的构造函数。