【问题标题】:Childs not loaded in multiple transactions with Hibernate未在 Hibernate 的多个事务中加载子项
【发布时间】:2013-10-28 11:56:37
【问题描述】:

这基本上是我的代码:

// 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 而不是所有其他信息。 Language 确实为 null 并生成异常。

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

你有什么想法吗?

【问题讨论】:

  • 您是否使用相同的代码从 DB 加载学校?你能分享那段代码吗?

标签: java mysql sql hibernate


【解决方案1】:

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

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

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-09-06
    • 2012-09-08
    • 1970-01-01
    • 2011-09-24
    • 1970-01-01
    • 2016-10-02
    相关资源
    最近更新 更多