0

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

谁能帮我?预先感谢!

4

2 回答 2

1

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

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

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

然后在哈希图中分配键属性值。

于 2013-04-09T09:47:08.563 回答
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>
于 2012-10-31T15:12:38.367 回答