java - Hibernate 对 group by 的查询

标签 java sql database hibernate hql

如何将此 postgreSql 查询转换为 hibernate 查询:

select sum(amount), cat_id, 
       date_trunc('month', createOn) as month,
       date_trunc('year', createOn) as year 
from item 
where owner_id = 1 
group by cat_id , month, year;

我的 Item 类为:

@Column(name="AMOUNT")
private BigDecimal amount;

@ManyToOne
@JoinColumn(name="OWNER_ID")
private Customer owner;


@ManyToOne(fetch=FetchType.EAGER)
@JoinColumn(name="CAT_ID")
private Category category;

@Temporal(TemporalType.DATE)
@Column(name="CREATEON")
private Date createOn;

我尝试将其转换为:

StringBuffer hql = new StringBuffer()
        .append("Select sum(amount), category, month(createOn) as mon, year(createOn) as year")
        .append(" from Item")
        .append(" where owner=:owner")
        .append(" group by category, mon, year");

    Query query = getQuery(hql.toString())
                    .setParameter("owner", owner);   

    List<Object[]> resultList = query.list();
    List<BundleHolder> bundleHolderList = new ArrayList<BundleHolder>();

    for(Object[] result : resultList) {
        BundleHolder instance = BundleHolder.getInstance();
        instance.setAmount((BigDecimal) result[0]);
        instance.setCategory((Category) result[1]);
        instance.setMonth((int) result[2]);
        instance.setYear((int) result[3]);

        bundleHolderList.add(instance);
    }

当我运行查询时,出现错误:

ERROR: org.hibernate.engine.jdbc.spi.SqlExceptionHelper - ERROR: column "category" does not exist

我尝试将类别切换为cat_id或将所有者切换为owner_id(将参数设置为owner.getId()),但这也没有帮助。

最佳答案

您需要将category更改为category.id:

StringBuffer hql = new StringBuffer()
        .append("Select sum(amount), category.id, month(createOn) as mon, year(createOn) as year")
        .append(" from Item")
        .append(" where owner=:owner")
        .append(" group by category.id, mon, year");

关于java - Hibernate 对 group by 的查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28131744/

相关文章:

java - 我不明白 eclipse 的错误

java - 在H2中使用 'FILE_LOCK=NO'安全吗?

database - 查询以列出 Datomic 中的所有分区

java - 如何制作由JAR和JRE组成的EXE文件

java - 如何编写java程序,使其输出以下行: (String)

java - 在 Eclipse 中匹配正则表达式环视

sql - MariaDB:COUNT DISTINCT 是否被窃听?

sql - 我需要使用 Over () 子句将单列中的 2 个计数值放在同一行中

python - sqlite3.OperationalError : near "WHERE": syntax error (Python 2, sqlite3)

SQL Server - 添加或减去先前的值