2009-07-01 56 views
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; 
} 
... 
+2

Criteria api沒有HQL那麼強大,您可以在HQL中查詢地圖。 – IAdapter 2009-07-01 22:15:53

回答

0

嘗試爲準則,創建別名。

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