Hibernate - 如何持久化HashMap

时间:2012-10-31 10:16:12

标签: java hibernate map hashmap persist

搜索Stackoverflow,我看到很多人都有同样的问题,但我找不到解决其他帖子的解决方案。所以:

我试图坚持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);

这是hbm.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()之前必须手动分配此类的ID

任何人都可以帮助我吗? 提前谢谢!

2 个答案:

答案 0 :(得分:1)

我解决了改变复合id属性的问题,如下所示:

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

mapped =“true”是解决方案的关键)

然后在hashmap中分配键属性值。

答案 1 :(得分:0)

简短回答:你的班级需要成为POJO。

答案很长:你需要为复合ID创建一个单独的类,比如

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>