【发布时间】:2011-05-24 08:31:03
【问题描述】:
我的 Hibernate 配置如下。
CPU型号:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="org.example.CPUModel" table="cpu_model">
<id name="cpuModelId" type="java.lang.Integer" unsaved-value="null">
<column name="cpu_model_id"/>
<generator class="identity"/>
</id>
<property name="name" type="java.lang.String">
<column length="32" name="name"/>
</property>
<set name="softwares" inverse="true" lazy="false" table="cpu_model_software" cascade="all-delete-orphan" order-by="cpu_sw_id desc">
<key>
<column name="cpu_model_id" not-null="true"/>
</key>
<one-to-many class="org.example.CPUModelSoftware"/>
</set>
</class>
</hibernate-mapping>
CPUModelSoftware
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="org.example.CPUModelSoftware" table="cpu_model_software">
<composite-id name="cpuModelSoftwarePK" class="org.example.CPUModelSoftwarePK">
<key-property name="cpuModelId" column="cpu_model_id" type="java.lang.Integer"/>
<key-property name="cpuSwId" column="cpu_sw_id" type="java.lang.Integer"/>
</composite-id>
<many-to-one class="org.example.CPUSoftware" insert="false" update="false" fetch="select" name="cpuSw">
<column name="cpu_sw_id" not-null="true"/>
</many-to-one>
</class>
</hibernate-mapping>
选择值和更新在这个配置下可以正常工作,但是插入一个全新的值就不行了。
我收到此错误:
DEBUG Could not execute JDBC batch update [insert into exampledb.cpu_model_software (cpu_model_id, cpu_sw_id) values (?, ?)]
java.sql.BatchUpdateException: Column 'cpu_model_id' cannot be null
因此,Hibernate 尝试进行插入,而无需先从数据库中获取生成的 cpu_model_id,然后将其设置为 CPUModelSoftwarePK(请参阅 CPUModel Hibernate 配置)
那么我如何告诉 Hibernate 它应该首先插入 cpu_model 表。然后从那里获取 id 并为 CPUModelSoftwarePK 设置 id 并进行插入?
CPUModelSoftware/PK的db如下。
+----------------+---------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+----------------+---------+------+-----+---------+-------+
| cpu_model_id | int(11) | NO | MUL | NULL | |
| cpu_sw_id | int(11) | NO | MUL | NULL | |
+----------------+---------+------+-----+---------+-------+
对于 CPU 模型
+----------------+------------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+----------------+------------------+------+-----+---------+----------------+
| cpu_model_id | int(11) unsigned | NO | PRI | NULL | auto_increment |
| name | varchar(32) | NO | | | |
+----------------+------------------+------+-----+---------+----------------+
编辑
在制作新的 CPUModelSoftware 时,我似乎没有将 CPUModelSoftwarePK 归零。但是现在我得到了这个:
ids for this class must be manually assigned before calling save(): org.example.CPUModelSoftware
【问题讨论】:
-
试试
<generator class="native"/>
标签: java hibernate foreign-keys one-to-many