HQL查询从@ElementCollection获取字段

时间:2015-01-16 15:18:35

标签: java hibernate hql

我正在尝试构造一个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)
  4. 这些都不起作用。

    是否可以获取此数据?如何确定要在我的HQL查询中使用的属性的名称?

1 个答案:

答案 0 :(得分:1)

加入该集合,然后使用 index()获取密钥 index(p)是关键, p 是值。

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