在下面给出的代码中,cascade =“save-update”用于与Student类关联的Course类(包)。
学生班是 - >
private int id;
private String firstName;
private String lastName;
private Address address;
private List<Course> courses;
课程类是 - &gt;
private int id;
private String name;
private int unit;
学生的hbm文件是 - &gt;
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate.Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="pojos.Student" table="Student">
<id name="id" type="integer" column="ID">
<generator class="increment" />
</id>
<property name="firstName">
<column name="FIRST_NAME" />
</property>
<property name="lastName">
<column name="LAST_NAME" />
</property>
<many-to-one name="address"
class="pojos.Address"
column="ADDRESS_ID"
cascade="save-update" />
<bag name="courses" inverse="true" cascade="save-update">
<key column="STUDENT_ID" />
<one-to-many class="pojos.Course" />
</bag>
</class>
</hibernate-mapping>
我正在执行的交易很简单 - &gt;
Student stud = new Student("Ketan", "Dikshit");
Address address = new Address("Dm-Road", "Uttar Pradesh", "201301");
Course course1 = new Course("Core Java", 101);
Course course2 = new Course("Advanced Java", 201);
List<Course> courses = new ArrayList<Course>();
courses.add(course1);
courses.add(course2);
stud.setAddress(address);
stud.setCourses(courses);
try {
tr = session.beginTransaction();
System.out.println("\n Transaction has begun..!!");
session.save(stud);
tr.commit();
System.out.println("\n Transaction is Commit..!!");
session.close();
System.out.println("\n Session is Closed..!!");
} catch (Exception e) {
System.out.println("\n Transaction is in errror..!!");
tr.rollback();
System.out.println("\n Transaction is RollBack..!!");
session.close();
System.out.println("\n Session is Closed..!!");
}
现在,根据代码,Courses表应该包含一个名为“STUDENT_ID”的列,其中相关学生的主键存在于Course表中的每个条目。但是“STUDENT_ID”列没有显示任何数据(插入所有空值)。
查询序列是 - &gt;
Transaction has begun..!!
Hibernate: select max(ID) from Student
Hibernate: select max(ID) from Address
Hibernate: select max(ID) from Course
Hibernate: insert into Address (STREET, CITY, ZIPCODE, ID) values (?, ?, ?, ?)
Hibernate: insert into Student (FIRST_NAME, LAST_NAME, ADDRESS_ID, ID) values (?, ?, ?, ?)
Hibernate: insert into Course (NAME, UNIT, ID) values (?, ?, ?)
Hibernate: insert into Course (NAME, UNIT, ID) values (?, ?, ?)
Transaction is Commit..!!
为什么Course表中的列显示NULL值,而不是保存Student的id?
答案 0 :(得分:1)
从包中删除inverse="true"
,否则此关系的所有者将是课程而不是学生。