1、错误描述
Exception in thread "main" org.hibernate.HibernateException: identifier of an instance of com.you.hibernate.model.TStudentInfo was altered from 6 to 7
at org.hibernate.event.internal.DefaultFlushEntityEventListener.checkId(DefaultFlushEntityEventListener.java:82)
at org.hibernate.event.internal.DefaultFlushEntityEventListener.getValues(DefaultFlushEntityEventListener.java:194)
at org.hibernate.event.internal.DefaultFlushEntityEventListener.onFlushEntity(DefaultFlushEntityEventListener.java:156)
at org.hibernate.event.internal.AbstractFlushingEventListener.flushEntities(AbstractFlushingEventListener.java:225)
at org.hibernate.event.internal.AbstractFlushingEventListener.flushEverythingToExecutions(AbstractFlushingEventListener.java:99)
at org.hibernate.event.internal.DefaultFlushEventListener.onFlush(DefaultFlushEventListener.java:51)
at org.hibernate.internal.SessionImpl.flush(SessionImpl.java:1214)
at org.hibernate.internal.SessionImpl.managedFlush(SessionImpl.java:403)
at org.hibernate.engine.transaction.internal.jdbc.JdbcTransaction.beforeTransactionCommit(JdbcTransaction.java:101)
at org.hibernate.engine.transaction.spi.AbstractTransactionImpl.commit(AbstractTransactionImpl.java:175)
at com.you.hibernate.dao.StudentDao.saveStuInfo(StudentDao.java:73)
at com.you.hibernate.dao.StudentDao.main(StudentDao.java:107)
2、错误原因
利用Hibernate批量添加,传入实体类参数,这里是用for循环进行批量添加;每循环一次,需要重新实例化实体类,但是却将实体类实例化放在循环外面
public static void main(String[] args)
{
TStudentInfo student = new TStudentInfo();
for(int i=10001;i<=100000;i++)
{
student.setId(i);
student.setStuNo(i);
student.setStuName("胡思思"+i);
student.setStuAge(20);
if(i%2==1)
{
student.setStuSex("女");
}
else
{
student.setStuSex("男");
}
student.setStuQq(""+i+"45744");
student.setStuAddr("湖南省长沙市");
saveStuInfo(student);
}
}
3、解决办法
public static void main(String[] args)
{
for(int i=10001;i<=100000;i++)
{
TStudentInfo student = new TStudentInfo();
student.setId(i);
student.setStuNo(i);
student.setStuName("胡思思"+i);
student.setStuAge(20);
if(i%2==1)
{
student.setStuSex("女");
}
else
{
student.setStuSex("男");
}
student.setStuQq(""+i+"45744");
student.setStuAddr("湖南省长沙市");
saveStuInfo(student);
}
}