0

这基本上是我的代码:

// Start first transaction to create a school

// Here I set a student for the school
school.setStudent(new Student(id));

// I Save

// Then I Start a SECOND transaction to retrieve the same school

// I can read the childs without prolem. 
school.getStudent().getLanguage().getId();

现在,由于某些原因,我希望上述所有内容都在同一个事务中。这就是发生的事情:

// Start the transaction to create a school

// Here I set a student that exist in the DB for that new school
school.setStudent(new Student(id));

// I Save

// In the same transaction I retrieve a list of schools, and one of the schools is the newly created.

// In the newly created school I can't access the childs: null pointer exception on language
school.getStudent().getLanguage().getId(); //ERRROR

第一种情况发生的情况是,即使我只为学生设置了id,一旦持久化,学生的所有其他信息都已经在数据库中,因为学生不是新的。我只是想和学校建立一个协会。

但在第二种情况下,我还没有终止交易,由于某些原因,当我再次查询学校时,学生只包含 id 而不是所有其他信息。语言确实为空并产生异常。

我尝试添加 session.flush() 但没有解决问题。

你有什么主意吗?

4

1 回答 1

0

您不想将学校学生设置为具有现有学生 ID 的新学生。您想将学校学生设置为现有学生。所以只需从数据库中获取它,而不是重新创建它:

Student theExistingStudent = (Student) session.load(Student.class, id);
school.setStudent(theExistingStudent);

上面甚至不会进行查询以从数据库中获取它。它将假定学生存在并向现有学生返回一个惰性初始化的代理。当然,如果你想确定学生确实存在,你也可以使用

Student theExistingStudent = (Student) session.get(Student.class, id);
school.setStudent(theExistingStudent);
于 2013-10-28T12:05:40.690 回答