那基本上就是我的代码:
// 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,由于该学生不是新来的,即使持久化了该学生的所有其他信息,该信息也已存储在数据库中。我只想与学校建立联系。
但是在第二种情况下,我仍然没有终止交易,由于某些原因,当我再次查询schhol时,学生仅包含id,而不包含所有其他信息。语言确实为null并生成异常。
我试图添加一个session.flush(),但没有解决问题。
你有什么主意吗?
最佳答案
您不想将学校学生设置为具有现有ID的新学生。您想要将学校学生设置为现有学生。因此,只需从数据库中获取它,而不是重新创建它:
Student theExistingStudent = (Student) session.load(Student.class, id);
school.setStudent(theExistingStudent);
上面的代码甚至不会查询从数据库中获取它。它将假定该学生存在,并将懒惰初始化的代理返回给现有学生。当然,如果要确保学生确实存在,也可以使用
Student theExistingStudent = (Student) session.get(Student.class, id);
school.setStudent(theExistingStudent);