休眠不插入外键
我有多对一的关系,当我试图插入一个值时,外键不通过。休眠不插入外键
Enitnty国家
<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>
当我创建了城市的实体,我在正确设置国家和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注释。
编辑:张贴国家和城市实体的完整映射。
update="false" insert="false"
在多对一的城市地图中适用于countryCode
和localeId
。由于localeId
也映射在您的composite-id中,所以在生成的查询中使用它,但countryCode
的情况并非如此...
那么解决这个问题的办法是什么?我应该创建一个FK(localeId2)来引用Country表。 – aumanets 2013-03-15 12:06:59
是的,我认为这是你最好的选择 – overmeulen 2013-03-15 13:20:21
您可以发布国家和城市的整个映射吗? – overmeulen 2013-03-15 11:30:25
@overmeulen我已经添加了国家和城市的整个映射。 – aumanets 2013-03-15 11:42:58
看到这里http://*.com/questions/804514/hibernate-field-id-doesnt-have-a-default-value – PSR 2013-03-15 11:45:47