2012-10-31 35 views
0

搜索Stackoverflow,我看到很多人都有我的同樣的問題,但我找不到解決方案看着其他職位。所以:Hibernate - 如何堅持一個HashMap

我想堅持一個Hibernate類,但沒有使用實體對象。相反,我正在使用一個地圖。

這是我的地圖:

Map<String, Object> record; 
record = new HashMap<String, Object>(); 

... 

record.put("key1", "value"); 
record.put("key2", "value"); 
record.put("field1", "value"); 
record.put("field2", "value"); 
record.put("field3", "value"); 
record.put("field4", "value"); 
record.put("field5", "value"); 
record.put("field6", value); 
record.put("field7", value); 

,這是你hml.xml

<class entity-name="entity_name" dynamic-update="true"> 
<composite-id name="Key1Key2" class="classname"> 
    <key-property name="Key1" column="Key1" type="string"/> 
    <key-property name="Key2" column="Key2" type="string"/> 
</composite-id> 
    <property name="field1" column="field1" type="string"/> 
    <property name="field2" column="field2" type="string"/> 
    <property name="field3" column="field3" type="string"/> 
    <property name="field4" column="field4" type="string"/> 
    <property name="field5" column="field5" type="string"/> 
    <property name="field6" column="field6" type="double"/> 
    <property name="field7" column="field7" type="double"/> 
</class> 

當我試圖堅持記錄:

super.session.persist("entity_name", record) 

返回此錯誤:

org.hibernate.id.IdentifierGenerationException:在調用save()之前必須手動分配此類的ids()

任何人都可以幫助我嗎? 提前致謝!

回答

0

簡答題:你的課程需要成爲POJO。

龍答:您需要創建複合標識一個單獨的類,像

public final class CompositeId implements Serializable { 
    private String first; 
    private String second; 

    // getters, setters, hashCode, equals 
} 

你的持久化對象將

public class YourClass { 
    private CompositeId id; 
    private Map map; 

    public YourClass() { 
    this.map = new HashMap(); 
    } 

    public void setId(CompositeId id) { 
    this.id = id; 
    } 

    public CompositeId getId() { 
    return id; 
    } 

    public void setField1(String field1) { 
    this.map.put("field1", field1); 
    } 

    public String getField1() { 
    return map.get("field1"); 
    } 
    // and so forth 
} 

最後,你的.hbm.xml:

<class entity-name="entity_name" dynamic-update="true"> 
<composite-id name="id" class="CompositeId"> 
    <key-property name="first" column="Key1" type="string"/> 
    <key-property name="second" column="Key2" type="string"/> 
</composite-id> 
    <property name="field1" column="field1" type="string"/> 
    <property name="field2" column="field2" type="string"/> 
    <property name="field3" column="field3" type="string"/> 
    <property name="field4" column="field4" type="string"/> 
    <property name="field5" column="field5" type="string"/> 
    <property name="field6" column="field6" type="double"/> 
    <property name="field7" column="field7" type="double"/> 
</class> 
+0

非常感謝你,我會盡快嘗試這個解決方案,並讓你知道它是否有效。 – Enrico

+0

該解決方案無效:出現此錯誤:類MyClass不能轉換爲java.util.Map – Enrico

1

我解決了這個問題,改變這樣的複合id屬性:

<composite-id class="CompositeId" mapped="true"> 

映射= 「真」是溶液的鍵)

,然後分配在HashMap中的關鍵屬性的值。