java - 如何在hibernate中查询map元素?

标签 java hibernate criteria

我有一个 hibernate 映射,如下所示:

<hibernate-mapping>
    <class name="MutableEvent" table="events"
        mutable="true" dynamic-insert="true" dynamic-update="true">

        <id name="id">
            <generator class="assigned" />
        </id>
        <property name="sourceTimestamp" />
        <property name="entryTimestamp" />

        <map name="attributes" table="event_attribs"
            access="field" cascade="all">
            <key column="id" />
            <map-key type="string" column="key" />
            <element type="VariantHibernateType">
                <column name="value_type" not-null="false" />
                <column name="value_string" not-null="false" />
                <column name="value_integer" not-null="false" />
                <column name="value_double" not-null="false" />
            </element>
        </map>

    </class>
</hibernate-mapping>

我的对象的存储和加载工作正常。我的问题是在 hibernate 中查询支持的 map ,我将如何使用标准 api 来做到这一点?

我想做这样的事情(这实际上是我的测试用例的一部分):

...
m.getAttributes().put("other", new Variant("aValue"));
this.storeEvent(MutableEvent.fromEvent(e));
getSession().clear();
MutableEvent m = (MutableEvent) getSession().get(MutableEvent.class, e.getId());
Assert.assertNotNull(m.getAttributes().get("other"));
Assert.assertEquals(new Variant("aValue"), m.getAttributes().get("other"));
Assert.assertNull(m.getAttributes().get("other2"));
getSession().clear();
crit = DetachedCriteria.forClass(MutableEvent.class);
crit.add(Restrictions.eq("attributes.other", new Variant("aValue")));
List l = this.findByCriteria(crit);
Assert.assertEquals(1, l.size());

重要的是,这会失败并显示“无法解析属性:attributes.other”:

crit.add(Restrictions.eq("attributes.other", new Variant("aValue")));
List l = this.findByCriteria(crit);

这个问题有解决办法吗?

更新

List l = find("from MutableEvent M where M.attributes['other'] = ?", new Variant("aValue"));

上面的代码没有抛出异常,但是查询本身仍然不是我想要的。我创建了一个自定义类型,正如人们通过映射看到的那样,实际上我想查询一个字符串(列 value_string),但任何修改查询以访问类型一部分的尝试,如 "from MutableEvent M where M.attributes['other'].string = ?" 不起作用。那么我该如何查询组件的一部分呢?

类型的实现如下:

...
private static final String[] PROPERTY_NAMES = { "type", "string", "integer", "double" };

public String[] getPropertyNames() {
    return PROPERTY_NAMES;
}
...

最佳答案

尝试为条件创建别名。

criteria.createAlias( "attributes", "as" );
criteria.add( Restrictions.ilike( "as.other", new Variant("aValue") );

关于java - 如何在hibernate中查询map元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1070440/

相关文章:

调用 WCF 的 Java 应用程序返回 "Connection Reset",而 SoapUI 工作正常

JAVA Commons-Net FTPClient,下载文件已损坏

java - Hibernate Criteria Limit 机制?

NHibernate 标准 API - 如何添加子句以将一个日期与另一个日期减去一个值进行比较

nhibernate - 对其他查询的结果执行 nHibernate icriteria(两个不同的查询)

Java - 正则表达式将第一个和最后一个字符一次性替换为另一个字符

java - Box2D:绳索摆(不停顿)

java - 如何在 Hibernate 中使用 mappedBy 更新集合类型关系?

删除ManyToOne记录后发生Spring Data JPA JpaObjectRetrievalFailureException

java - 混合jpa继承策略-inheritanceType.JOINED与inheritanceType.SINGLE_TABLE