private int id; -6ren">
gpt4 book ai didi

java - 级联在 hibernate 模式下无法正常工作

转载 作者:行者123 更新时间:2023-11-29 14:01:38 24 4
gpt4 key购买 nike

在下面给出的代码中,cascade="save-update"用于与 Student 类关联的 Course 类(包)。

学生类(class)是-->

    private int id;
private String firstName;
private String lastName;
private Address address;
private List<Course> courses;

类(class)类别是-->

    private int id;
private String name;
private int unit;

学生的 hbm 文件是-->

<?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>

我正在执行的交易很简单-->

                    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..!!");
}

现在,根据代码,类(class)表应该包含一个名为“STUDENT_ID”的列,其中包含类(class)表中每个条目的关联学生的主键。但是“STUDENT_ID”列没有显示任何数据(插入所有空值)。

查询顺序是-->

 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..!!

为什么类(class)表中的列显示 NULL 值,而不是保存学生的 ID?

最佳答案

从您的包映射中删除 inverse="true",否则此关系的所有者将是类(class)而不是学生。

关于java - 级联在 hibernate 模式下无法正常工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14980308/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com