3
我有一个Hibernate映射它看起来像这样:如何查询hibernate中的map元素?
<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的地图,以及如何使用标准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 =?“不起作用。那么,我将如何查询组件的一部分?
类型为实现这样的:
...
private static final String[] PROPERTY_NAMES = { "type", "string", "integer", "double" };
public String[] getPropertyNames() {
return PROPERTY_NAMES;
}
...
Criteria api没有HQL那么强大,您可以在HQL中查询地图。 – IAdapter 2009-07-01 22:15:53