【问题标题】:Store non existence column in JPA entity when it is used as Alias in SQL在 JPA 实体中存储不存在列作为 SQL 中的别名
【发布时间】:2012-09-17 07:25:22
【问题描述】:

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

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

【问题讨论】:

  • 您的问题不清楚。您是否尝试通过 EntityManager.createNativeQuery 运行此查询?如果是这样,不确定“作为实体检索”是什么意思。
  • @SteveEbersole :如果我写为本机查询,我需要分配给实体类。本机查询的结果分配给映射列的实体。此外,如果我有像 locCount 这样的额外列,我该如何映射?

标签: java sql hibernate jpa


【解决方案1】:

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

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 变量 setter 方法。这样您就可以获得您的计数


试试这样

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();

干杯!!!

【讨论】:

  • 这两种方法都行不通。结果不能设置为“@transient”变量。第二个查询将返回可用记录的总数。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-07-16
  • 1970-01-01
  • 2016-03-31
  • 1970-01-01
  • 1970-01-01
  • 2012-04-01
  • 2014-03-05
相关资源
最近更新 更多