【问题标题】:How to query for map element in hibernate?如何在休眠中查询地图元素?
【发布时间】:2010-11-07 09:54:12
【问题描述】:

我有一个如下所示的休眠映射:

<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>

我的对象的存储和加载工作正常。我的问题是查询支持休眠的地图,我将如何使用标准 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),但是任何修改查询以访问类型的一部分的尝试,如来自 MutableEvent M 的 " M.attributes['other'].string = ?" 不起作用。那么如何查询组件的一部分呢?

Type 是这样实现的:

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

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

【问题讨论】:

  • Criteria api不如HQL强大,可以在HQL中查询map。

标签: java hibernate criteria


【解决方案1】:

尝试为条件创建别名。

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-08-10
    • 2011-08-09
    相关资源
    最近更新 更多