Hibernate异常:identifier of an instance of 错误
今天写项目时,在使用hibernate封装的插入方法时,由于需要同时保存多个数据,导致出现identifier of an instance of
如下代码 :(由于最大最小分数不同所以需要插入两条数据)
ExamScoreDivide examScoreDivide=new ExamScoreDivide(); ExamCourse examCourse=new ExamCourse(); examCourse.setExamCourseId(examCourseId); Exam exam=new Exam(); exam.setExamId(examId); examScoreDivide.setDivideId(StringUtil.getUuid()); examScoreDivide.setMinScore(minScore1); examScoreDivide.setMaxScore(maxScore1); examScoreDivide.setExamCourse(examCourse); examScoreDivide.setExam(exam); examScoreDivide.setCreator(userInfo.getUserName()); examScoreDivide.setCreateTime(DateUtil.currentDate()); examScoreDivide.setDivideName(divideName); gradExamScoreDivideService.save(examScoreDivide); examScoreDivide.setDivideId(StringUtil.getUuid()); examScoreDivide.setMinScore(minScore2); examScoreDivide.setMaxScore(maxScore2); examScoreDivide.setExamCourse(examCourse); examScoreDivide.setExam(exam); examScoreDivide.setCreator(userInfo.getUserName()); examScoreDivide.setCreateTime(DateUtil.currentDate()); examScoreDivide.setDivideName(divideName); gradExamScoreDivideService.save(examScoreDivide);
但结果报该错误,后来知道了原因:
报错的原因是,在没有给对象examScoreDivide 分配初始的内存地址的时候,就进行对象生成,不管生成多少个,都是多个对象的内存指针指向一个内存地址,所以hibernate在存储时就会保存。放在内存里面每次new就等一个新的内存空间,所以不会报错。
解决后的代码:
ExamScoreDivide examScoreDivide=new ExamScoreDivide(); ExamCourse examCourse=new ExamCourse(); examCourse.setExamCourseId(examCourseId); Exam exam=new Exam(); exam.setExamId(examId); examScoreDivide.setDivideId(StringUtil.getUuid()); examScoreDivide.setMinScore(minScore1); examScoreDivide.setMaxScore(maxScore1); examScoreDivide.setExamCourse(examCourse); examScoreDivide.setExam(exam); examScoreDivide.setCreator(userInfo.getUserName()); examScoreDivide.setCreateTime(DateUtil.currentDate()); examScoreDivide.setDivideName(divideName); gradExamScoreDivideService.save(examScoreDivide); ExamScoreDivide examScoreDivide1=new ExamScoreDivide(); ExamCourse examCourse1=new ExamCourse(); examCourse1.setExamCourseId(examCourseId); Exam exam1=new Exam(); exam1.setExamId(examId); examScoreDivide1.setDivideId(StringUtil.getUuid()); examScoreDivide1.setMinScore(minScore2); examScoreDivide1.setMaxScore(maxScore2); examScoreDivide1.setExamCourse(examCourse1); examScoreDivide1.setExam(exam1); examScoreDivide1.setDivideName(divideName); examScoreDivide1.setCreator(userInfo.getUserName()); examScoreDivide1.setCreateTime(DateUtil.currentDate()); gradExamScoreDivideService.save(examScoreDivide1);