【发布时间】:2013-03-03 23:30:15
【问题描述】:
我有多对一的关系,当我尝试插入一个值时,没有传递前键。
实体国家
<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 注释。
编辑:发布了国家和城市实体的完整映射。
【问题讨论】:
-
你能把国家和城市的整个地图贴出来吗?
-
@overmeulen 我已经添加了国家和城市的整个映射。
-
@PSR 我已经探讨过这个问题,但没有成功,似乎这里的问题有所不同。谢谢
标签: hibernate orm foreign-keys mapping reverse-engineering