你好,我有一个这样的片段。
public void update(Student student)
{
student=super.merge(student);
currentSession().update(student);
return;
}
但有时这段代码会抛出
java.lang.IllegalArgumentException: attempt to create saveOrUpdate event with null entity.
我想知道这种可能的合并在任何环境中如何都会返回null?
因为我已经检查Student
不为空,因为如果为merge
则会抛出。
Exception in thread "main" java.lang.IllegalArgumentException: attempt to create merge event with null entity
我认为发生这种事情的唯一情况是,如果merge
返回null,这可能吗?
对不起,如果这个问题很简单,那么感谢委内瑞拉的最好问候。
答案 0 :(得分:1)
merge()用于将分离的对象与附加对象合并(两者具有相同的id)。例如,您在方法update()中传入了一个student1对象,该对象具有一个id并且其状态是分离的:
public void update(Student student1)
{
//student1 is in detached status, you may modify it if not yet done
student1.setName("ABC");
//now load a student2 from db with the same id, note student2 is in persistent status
Student student2 = currentSession().load(Student.class, student1.getId());
//merge student1 to student2 and return a new student3
Student student3 = currentSession().merge(student1);
//--done, checkout student3, you will see "ABC" is merged. You can't call update() in this case.
return;
}
如果您只想更新传入的学生,请删除student=super.merge(student);
,调用saveOrUpdate(),如下所示:
public void update(Student student)
{
currentSession().saveOrUpdate(student);
return;
}