【问题标题】:HQL Query to get fields from @ElementCollection从@ElementCollection 获取字段的 HQL 查询
【发布时间】:2015-03-15 05:51:45
【问题描述】:

我正在尝试构建一个 HQL 查询以从 @ElementCollection 中提取属性:

public class Resource {
  @Id
  private String name;

  @ElementCollection()
  @CollectionTable(
          name = "property",
          )
  @SortNatural
  private final SortedMap<String, String> properties =
        Maps.newTreeMap();
}

property 表使用默认列名(propertiesproperties_key)来存储数据(使用外键返回我的资源表)。

我有以下 HQL 查询,我试图在其中返回键和值。

final Query q = session.createQuery("select new list(r.name, elements(r.properties)) from Resource r where r.name like :nameFilter");

这是有效的,当我调用q.list() 时,我得到一个包含名称和值的对象列表。我遇到的问题是我无法弄清楚如何获取与值关联的键。即properties_key 列中的数据。

我尝试过的事情:

  1. 元素(r.properties_key)
  2. 元素(r.propertiesKey)
  3. 元素(r.key)

这些都不起作用。

是否可以将这些数据取出来?如何确定要在 HQL 查询中使用的属性名称?

【问题讨论】:

    标签: java hibernate hql


    【解决方案1】:

    加入集合,然后使用index()获取key。
    index(p)是key,p是价值。

    List list = currentSession.createQuery(
    "select new list(s.id, index(p), p) from Resource s join s.properties p").list();
    

    【讨论】:

    • 非常感谢,我遇到了完全相同的问题,这就是我的解决方案。这完全是晦涩难懂的!
    猜你喜欢
    • 2012-12-14
    • 1970-01-01
    • 1970-01-01
    • 2016-04-21
    • 1970-01-01
    • 1970-01-01
    • 2017-07-18
    • 2012-03-13
    • 1970-01-01
    相关资源
    最近更新 更多