我有 2 个班级,学生和班级。每个学生只能是一个班级的一部分。
我正在尝试使用以下代码插入学生
for (Class cls : classList) {
if (cls.getId().getClassId() == selectedClassId.intValue()) {
selectedStudent.setClass(cls);
}
}
HibernateUtil.beginTransaction();
StudentHome stuhome = new StudentHome();
stuhome.persist(selectedStudent);
HibernateUtil.commitTransaction();
但是由于某种原因,Hibernate 没有在 Student 表中插入 classId 字段。
下面是我从 Hibernate 得到的 SQL 输出
Hibernate:
select
class_.ClassId,
class_.EntityId,
class_.ClassName as ClassName2_
from
school.class102 class_
where
class_.ClassId=?
and class_.EntityId=?
Hibernate:
insert
into
school.student102
(StudentId, ParentId, RouteId, FirstName, LastName, MiddleName, DoB, DoJ, DoL, Status, RegistrationId, EntityId)
values
(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
如您所见,插入语句中显然缺少 classId。我不确定 Hibernate 是否没有在插入语句中包含 classId。
EntityId 和 RegistrationId 是 Student 和 EntityId 的 PK,ClassId 是 Class 的 PK。两个表中都存在与 (EntityId, ClassId) 的外键关系。通过具有预定义 EntityId 的视图尝试插入
可能是什么问题?
下面是映射
<hibernate-mapping>
<class name="Student" table="student104" catalog="school">
<composite-id name="id" class="studentId">
<key-property name="registrationId" type="int">
<column name="RegistrationId" />
</key-property>
<key-property name="entityId" type="int">
<column name="EntityId" />
</key-property>
</composite-id>
<many-to-one name="class" class="class" update="false" insert="false" fetch="select">
<column name="ClassId" />
<column name="EntityId" not-null="true" />
</many-to-one>
<property name="studentId" type="java.lang.Integer">
<column name="StudentId" />
</property>
<property name="parentId" type="java.lang.Integer">
<column name="ParentId" />
</property>
<property name="routeId" type="java.lang.Integer">
<column name="RouteId" />
</property>
<property name="firstName" type="string">
<column name="FirstName" length="45" />
</property>
<property name="lastName" type="string">
<column name="LastName" length="45" />
</property>
<property name="middleName" type="string">
<column name="MiddleName" length="45" />
</property>
<property name="doB" type="date">
<column name="DoB" length="10" />
</property>
<property name="doJ" type="date">
<column name="DoJ" length="10" />
</property>
<property name="doL" type="date">
<column name="DoL" length="10" />
</property>
<property name="status" type="string">
<column name="Status" length="45" />
</property>
</class>
<hibernate-mapping>
<class name="class" table="class102" catalog="school">
<composite-id name="id" class="classId">
<key-property name="classId" type="int">
<column name="ClassId" />
</key-property>
<key-property name="entityId" type="int">
<column name="EntityId" />
</key-property>
</composite-id>
<property name="className" type="string">
<column name="ClassName" length="45" not-null="true" />
</property>
<set name="students" table="student104" inverse="true" lazy="true" fetch="select">
<key>
<column name="ClassId" />
<column name="EntityId" not-null="true" />
</key>
<one-to-many class="student" />
</set>
</class>