Hibernate本机查询显示异常

时间:2015-01-13 04:59:44

标签: java sql hibernate orm hibernate-criteria

我编写了hibernate本机查询,用于从表中获取总用户数和月数 但它显示:

exception:Operand should contain 1 column(s)
org.hibernate.exception.DataException: could not execute query

任何人都可以帮我解决这个问题:

  c.setProjection(Projections.projectionList()
     .add(Projections.sqlProjection("(select count(*), MONTH(Stored) from adbtbl_stat " 
     + "where Activity = 89 and YEAR(Stored) = 2015) as Count, month",
     new String[] { "Count", "month" }, new Type[] { LongType.INSTANCE, StringType.INSTANCE }))
     .add(Projections.groupProperty(month(stored))));

1 个答案:

答案 0 :(得分:1)

ProjectionList可以包含多个SQLProjection(s),但每个SQLProjection应该只与一个SQL列相关联。

您的SQLProjection尝试选择两列。

尝试使用简单的原生查询替换您的Criteria查询:

Long activity = ...;
int year = ...;

Query q = entityManager.createNativeQuery(
    "select count(*) as Count, MONTH(Stored) as Month " +
    "from adbtbl_stat " +
    "where Activity = :activity and YEAR(Stored) = :year"
);
q.setParameter("activity", activity);
q.setParameter("year", year);
List<Object[]> result = (List<Object[]>) q.getResultList();