java - 当在 SQL 中用作别名时,将不存在的列存储在 JPA 实体中

标签 java sql hibernate jpa

我编写了一个查询来计算指定企业下可用的位置数量。 SQL 查询是这样的

SELECT 
e.enterprise_id,
e.ent_name,
(
    SELECT count(l.location_id)
    FROM rfx_ent_locations l
    WHERE l.loc_type_id <> 1001
        AND e.enterprise_id = l.enterprise_id
) AS locCount
FROM rfx_enterprises e
WHERE  e.partner_type = 102;

如果作为实体中的列引入,我会收到一条错误消息,提示未找到列。要使用 JPA 检索包含用作别名的 locCount 的实体,我应该如何进行?

最佳答案

不要用那个做你的计数查询。像这样单独做

Query query = session.createQuery("SELECT count(l.location_id)
    FROM rfx_ent_locations l
    WHERE l.loc_type_id <> 1001
        AND e.enterprise_id = l.enterprise_id");// do as you please with the query result

    /**
     * instead of doing a second query to get the count.  Just do a quick count using Iterator
     */

    for (Iterator iterator = query.iterate(); iterator.hasNext();) {
        iterator.next();
        count++;
    }

    Integer queryCount = count;

将此 queryCount 设置为您类中的@transient 变量设置方法。这样您就可以得到您的计数


像这样尝试

Integer count = (Integer) session.CreateQuery("SELECT count(l.location_id)
FROM rfx_ent_locations l
WHERE l.loc_type_id <> 1001
    AND e.enterprise_id = l.enterprise_id").UniqueResult();

干杯!!!

关于java - 当在 SQL 中用作别名时,将不存在的列存储在 JPA 实体中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12454774/

相关文章:

java - 在 src 目录中的 eclipse 中添加文件夹而不使其打包

java - 指向 JPA/Hibernate 中同一实体的多个 @ManyToOne 字段

java - for循环在android try-catch block 中不起作用

java - 针对时间戳列的 Oracle SQL where 子句

java - Keytool 认为 cacerts 不存在

sql - Oracle SQL - 从给定的字符串形成一个虚拟表以与另一个表连接

sql - 删除具有特定列值的所有行(每个用户的最新行除外)

c# - foreach 列表框中的项目 |阅读器

java - 为什么 hibernate 在第 1 行抛出 "data truncation-data too long for coloumn ' a'?

java - Jaxb Moxy 与 Hibernate?在 Jboss 6.1 上