我编写了一个查询来计算指定企业下可用的位置数量。 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/