1

我有多对一的关系,当我尝试插入一个值时,没有传递前键。

实体国家

<hibernate-mapping>
<class name="servicedb.dal.domain.Country" table="Country" catalog="DB">
    <composite-id name="id" class="servicedb.dal.domain.CountryId">
        <key-property name="countryCode" type="string">
            <column name="countryCode" length="2" />
        </key-property>
        <key-property name="localeId" type="int">
            <column name="localeId" />
        </key-property>
    </composite-id>
    <many-to-one name="locale" class="servicedb.dal.domain.Locale" update="false" insert="false" fetch="select">
        <column name="localeId" not-null="true" />
    </many-to-one>
    <property name="name" type="string">
        <column name="name" length="60" not-null="true" />
    </property>
    <set name="cities" table="City" inverse="true" lazy="true" fetch="select">
        <key>
            <column name="countryCode" length="2" not-null="true" />
            <column name="localeId" not-null="true" />
        </key>
        <one-to-many class="servicedb.dal.domain.City" />
    </set>
</class>

实体城

<hibernate-mapping>
    <class name="servicedb.dal.domain.City" table="City" catalog="DB">
        <composite-id name="id" class="servicedb.dal.domain.CityId">
            <key-property name="id" type="int">
                <column name="id" />
            </key-property>
            <key-property name="localeId" type="int">
                <column name="localeId" />
            </key-property>
        </composite-id>
        <many-to-one name="country" class="servicedb.dal.domain.Country" update="false" insert="false" fetch="select">
            <column name="countryCode" length="2" not-null="true" />
            <column name="localeId" not-null="true" />
        </many-to-one>
        <property name="name" type="string">
            <column name="name" length="100" not-null="true" />
        </property>
        <set name="localizedLocations" table="LocalizedLocation" inverse="true" lazy="true" fetch="select">
            <key>
                <column name="cityId" />
                <column name="localeId" not-null="true" />
            </key>
            <one-to-many class="servicedb.dal.domain.LocalizedLocation" />
        </set>
    </class>
</hibernate-mapping>

当我创建 City 实体时,我正确设置了 Country 并且 countryCode 不为空。但生成的查询如下所示:

insert into Db.City (name, id, localeId) values (?, ?, ?)

但它应该是:

insert into Db.City (name, id, localeId, countryCode) values (?, ?, ?, ?)

并且休眠抛出以下异常

org.hibernate.exception.GenericJDBCException: Field 'countryCode' doesn't have a default value

我希望提供的信息足以了解错误的原因。如果没有,请专门询问其他信息。

我还使用 eclipse 和 reveng.xml 对数据库进行逆向工程,所以我的hbm文件是自动生成的,我没有使用 EJB3 注释。

编辑:发布国家和城市实体的完整映射。

4

1 回答 1

1

您的update="false" insert="false"City 映射中的多对一适用于countryCodelocaleId。由于localeId也映射在您的复合 ID 中,因此它用于生成的查询中,但countryCode...

于 2013-03-15T11:56:00.440 回答