如何处理复合键休眠

时间:2012-10-03 11:56:11

标签: java hibernate java-ee hibernate-mapping

我的hbm.xml文件是这样的:

<hibernate-mapping>
<class name="pojopackage.WordhelperWordusage" table="WORDHELPER_WORDUSAGE" schema="SOZANA">
    <composite-id name="id" class="pojopackage.WordhelperWordusageId">
        <key-property name="idwh" type="java.lang.Integer">
            <column name="IDWH" />
        </key-property>
        <key-property name="idwu" type="java.lang.Integer">
            <column name="IDWU" />
        </key-property>
        <key-property name="type" type="java.lang.Integer">
            <column name="TYPE" />
        </key-property>
    </composite-id>
    <many-to-one name="wordhelper" class="pojopackage.Wordhelper" update="false" insert="false" fetch="select">
        <column name="IDWH" />
    </many-to-one>
    <many-to-one name="wordusage" class="pojopackage.Wordusage" update="false" insert="false" fetch="select">
        <column name="IDWU" />
    </many-to-one>
</class>

但我有两个POJO类,分别是“WordhelperWordusage.java”和“WordhelperWordusageId.java”,所以我很困惑,我应该如何处理这些类?如何实施?提前致谢! 的更新

我确实喜欢这个

wordhelper_wordusage.save(wordhelper);
wordhelper_wordusage.save(wordusage);
session.save(wordhelper);
session.save(wordusage);
session.save(wordhelper_wordusage);

但它给我这样的例外:

Hibernate: select max(ID) from SOZANA.WORDFORM
Hibernate: select max(ID) from SOZANA.WORDHELPER
Exception in thread "main" org.hibernate.id.IdentifierGenerationException:
ids for this   class must be manually assigned before calling save():   pojopackage.WordhelperWordusage

3 个答案:

答案 0 :(得分:2)

复合PK通常映射到PK类,以便Hibernate可以正确处理它们。您发布的映射就是这种情况。请注意,如果您忽略WordhelperWordusage元素中的class属性,则可以将这些PK属性映射到同一个<composite-id>类中,这不是必须使用PK类的。 (但不建议这样做)。有关详细信息,请参阅此相关问题:hibernate composite key

至于给定映射文件的实现,是否足以在映射中创建具有属性的类?

package pojopackage;

public class WordhelperWordusage { 

    private WordhelperWordusageId id;
    private Wordhelper wordhelper;
    private Wordusage wordusge;

    // Getters / Setters

    // Implement equals() and hashCode() delegating to id
}

package pojopackage;

public class WordhelperWordusageId { 
    private Integer idwu;
    private Integer type;

    // Getters / setters

    // Implement equals() and hashCode() consistently, using idwu and type.

}

请务必在这些类中始终如一地实施hashCode()equals()。因此,WordhelperWordusage的哈希码是其ID的哈希码,并且当且仅当它们的id相等时它们才相等。对于id类,只需散列两个Integer属性,并将它们与equals()进行比较。

答案 1 :(得分:0)

WordhelperWordusageId.java类用于构建主键。它有两个属性idwh和idwu。这些属性的组合定义了主键。 Hibernate为复合键创建了对象,并重写了equals和hashCode方法。此对象用于标识主WordhelperWordusage.java对象的键。所以为简单起见,将对象视为简单的id列属性,唯一的区别是这是对象而不是简单属性,否则所有规则都应用于ID。异常生成器方案。

答案 2 :(得分:0)