7

I am using Hibernate 3.2.5. I am getting the above exception while using many-to-one mapping. The training table is having a many to one relation with Department table, i.e. One Depatement is capable of taking more than one training.

The exception is asking me to add insert="false" update="false" in my hbm file. If I add this bit in hbm file, then the code works fine.

Here is the hbm file:

<?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="com.infy.model.Training" table="training">
  <id name="Id" type="integer" column="ID">
      <generator class="assigned"></generator>
  </id>      
  <property name="trainerName">
      <column name="TRAINER_NAME"></column>
  </property>
  <property name="deptId">
      <column name="DEPT_ID"></column>
  </property>
  <property name="trainingSubject">
      <column name="TRAINING_SUBJECT"></column>
  </property>
  <many-to-one name="departmentDetails" column="DEPT_ID"></many-to-one>
  </class>
</hibernate-mapping>

If I change this line to:

<many-to-one name="departmentDetails" column="DEPT_ID" insert="false" update="false"></many-to-one>

Then the code works. I want to know what is the exact reason for adding this.

Regards,

4

3 回答 3

8

您已经映射了 DEPT_ID 列两次,这里:

  <property name="deptId">
      <column name="DEPT_ID"></column>
  </property>

和这里:

  <many-to-one name="departmentDetails" column="DEPT_ID"></many-to-one>

执行 select 语句时,Hibernate 可以很好地从同一列填充对象的两个属性,但是在执行插入或更新时,它无法决定将哪个属性保留在数据库中。

为什么首先需要将两个属性映射到同一列?如果您需要访问 deptId,您可以删除 deptId 属性并改为

training.getDepartmentDetails().getId()
于 2012-11-10T15:07:02.653 回答
6

这个场景的错误信息很清楚(你没有放在这里,但我已经看过几次了)。问题是您已将该列映射DEPT_ID到班级中的两个不同字段。

首先,您已将其映射到属性deptId,然后映射到departmentDetails. 正如您所发现的,只有当其中一个映射配置为insert="false" update="false".

原因很简单。如果要更改deptId为另一个 id,则 hibernate 需要更改映射到的类departmentDetails,这非常复杂。

如果您需要获取 deptId,您可以在Training该返回上添加一个 getDeptId 方法departmentDetails.getId()。并且不提供setDeptId.

于 2012-11-10T15:05:42.390 回答
1

如果您在映射文件中两次使用相同的列名。可能是你得到映射异常

Initial SessionFactory creation failed.org.hibernate.MappingException:

另外,如果您标记 insert=flase 和 update=false 。

如果您尝试更新或插入表或其他遗留系统中的记录,请尝试更新这些列值。它不会更新或插入该文件。

请检查以下链接。它将帮助您找到解决方案。

http://www.techienjoy.com/hibernate-insert-update-control.php

谢谢桑迪普 G。

于 2012-11-10T22:23:37.873 回答