object references an unsaved transient instance - save the transient instance before flushing

版权声明:本文为博主原创文章,未经允许不得转载。 https://blog.csdn.net/MOESECSDN/article/details/79947860

错误提示后面还有一些提示,提示是哪个对象出现问题!

原因可能是:我们没有给这个对象赋值,此时 Hibernate 会 new 一个 空对象 保存给这个对象,空对象在数据库肯定是没有的,即提示所说的unsaved
transient instance(未保存状态的临时实例 或者说 游离态)提示我们要先保存! 所以在保存该对象的时候就会错误。
解决的办法是:
1. 判断对象是否为空,空的话,直接设置这个对象为空(null)或者给个默认值,而不是给它个空对象!

例如:

//如果不填部门则默认为该员工所在的部门
            if (task.getDept()==null || task.getDept().getId()==null) {
                //task.setDept(null);
                Employee employee = empService.get(task.getEmp().getId());
                task.setDept(employee.getDept());
            }

如果您还有其他解决办法,或者觉得我所言有错误,欢迎留言。

阅读更多

ManyToOne单向配置(错误:object references an unsaved transient instance - save the transient instance before flushing:)

12-18

[code=Java]rn@ManyToOne(fetch=FetchType.LAZY,optional=true) rn @JoinColumn(name = "MAINTAINER",referencedColumnName="ID")rn public User getMaintainer() rn return this.maintainer;rn rn rn public void setMaintainer(User maintainer) rn this.maintainer = maintainer;rn rn[/code]rnrn代码如上,这个是Ci对象的一个属性(User类型的)ci和user是多对一的关系,user表没有设置ci信息的外键,二者也没有中间表。在插入Ci信息的时候,也传给了maintainer的id(此Id肯定在Use表里面是存在的)。但是就是报如下错误:rnrn严重: Servlet.service() for servlet default threw exceptionrnorg.hibernate.TransientObjectException: object references an unsaved transient instance - save the transient instance before flushing: com.dhcc.itsm.base.model.Userrnrn原因好像是:由于保存Ci时,User还是瞬时态,所以不能保存,而必须User是持久态(在此程序里面就是在保存时根据UserId查处此User对象的信息)才能保存成功。但是我这个ci对象里面有8个对象,一个个手工去查一遍再保存,很累人,况且ci的对象里面还有对象,这样就必须是有的子对象也先查一遍,估计这样的话至少有30多个对象要先查。所以应该可以有其他的解决办法。rn希望那位能够帮忙解决只配置Ci这一方的ManyToOne是否就能实现增加。rn

hibernate的一个问题:object references an unsaved transient instance - save the transient instance before

04-24

我就是做了一对多和多对一的双向关联,我关联查询的时候会报错。这个异常我搜过的。但是还是没有解决问题。异常如下:rn21:57:42.218 [http-8080-1] DEBUG org.hibernate.jdbc.AbstractBatcher - about to close PreparedStatement (open PreparedStatements: 1, globally: 1)rn21:57:42.218 [http-8080-1] DEBUG o.h.transaction.JDBCTransaction - rollbackrn21:57:42.218 [http-8080-1] DEBUG o.h.transaction.JDBCTransaction - re-enabling autocommitrn21:57:42.218 [http-8080-1] DEBUG o.h.transaction.JDBCTransaction - rolled back JDBC Connectionrn21:57:42.218 [http-8080-1] DEBUG org.hibernate.jdbc.ConnectionManager - transaction completed on session with on_close connection release mode; be sure to close the session to release JDBC resources!rn21:57:42.218 [http-8080-1] DEBUG org.hibernate.impl.SessionImpl - disconnecting sessionrn21:57:42.218 [http-8080-1] DEBUG org.hibernate.jdbc.ConnectionManager - releasing JDBC connection [ (open PreparedStatements: 0, globally: 0) (open ResultSets: 0, globally: 0)]rn21:57:42.218 [http-8080-1] DEBUG org.hibernate.jdbc.ConnectionManager - transaction completed on session with on_close connection release mode; be sure to close the session to release JDBC resources!rn2009-4-24 21:57:42 org.apache.catalina.core.StandardWrapperValve invokern严重: Servlet.service() for servlet xiaoyuBlog threw exceptionrnorg.hibernate.TransientObjectException: object references an unsaved transient instance - save the transient instance before flushing: org.blog.blog.domain.Userrn at org.hibernate.engine.ForeignKeys.getEntityIdentifierIfNotUnsaved(ForeignKeys.java:242)rn at org.hibernate.type.EntityType.getIdentifier(EntityType.java:430)rn at org.hibernate.type.ManyToOneType.nullSafeSet(ManyToOneType.java:110)rn at org.hibernate.loader.Loader.bindPositionalParameters(Loader.java:1728)rn at org.hibernate.loader.Loader.bindParameterValues(Loader.java:1699)rn at org.hibernate.loader.Loader.prepareQueryStatement(Loader.java:1589)rn at org.hibernate.loader.Loader.doQuery(Loader.java:696)rn at org.hibernate.loader.Loader.doQueryAndInitializeNonLazyCollections(Loader.java:259)rnrn下面是我的HBM配置:rnrnrnrn rn rn rn rn rn rn rn rn rn rn rn rnrn下一个是:rnrnrnrn rn rn rn rn rn rn rn rn rn rn rn rn rnrnrn我配置的文件,我WEB层调用的方法是:rnUser user=(User)request.getSession().getAttribute("user");rn List articles=articleManager.findByProperty("createUser", user);rn我提供了getter和setter方法的。但是总报这个错误。在这个地方也报:rnUser user=(User)request.getSession().getAttribute("user");rn article.setCreateUser(user);rn article.setCreateDate(new Date());rn articleManager.save(article);rn我很想彻底解决这个问题,它的意思就是麽有把对象持久,user对象没有持久就保存。

求助!!! object references an unsaved transient instance 怎么解决

02-21

rnorg.springframework.dao.InvalidDataAccessApiUsageException: object references an unsaved transient instance - save the transient instance before flushing: cn.edu.hust.job.data.entity.Sex; nested exception is org.hibernate.TransientObjectException: object references an unsaved transient instance - save the transient instance before flushing: cn.edu.hust.job.data.entity.Sexrn at org.springframework.orm.hibernate3.SessionFactoryUtils.convertHibernateAccessException(SessionFactoryUtils.java:634)rn at org.springframework.orm.hibernate3.HibernateTransactionManager.convertHibernateAccessException(HibernateTransactionManager.java:728)rn at org.springframework.orm.hibernate3.HibernateTransactionManager.doCommit(HibernateTransactionManager.java:604)rn at org.springframework.transaction.support.AbstractPlatformTransactionManager.processCommit(AbstractPlatformTransactionManager.java:709)rn at org.springframework.transaction.support.AbstractPlatformTransactionManager.commit(AbstractPlatformTransactionManager.java:678)rn at org.springframework.transaction.interceptor.TransactionAspectSupport.commitTransactionAfterReturning(TransactionAspectSupport.java:319)rn at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:116)rn at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:171)rn at org.springframework.aop.interceptor.ExposeInvocationInterceptor.invoke(ExposeInvocationInterceptor.java:89)rn at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:171)rn at org.springframework.aop.framework.Cglib2AopProxy$DynamicAdvisedInterceptor.intercept(Cglib2AopProxy.java:635)rn at cn.edu.hust.job.user.dao.GraduateDao$$EnhancerByCGLIB$$c41435dd.save()rn at cn.edu.hust.job.graduate.service.GraduateServiceImpl.save(GraduateServiceImpl.java:106)rn at cn.edu.hust.job.graduate.action.StudentInfoAction.importDoctorStudent(StudentInfoAction.java:931)rn at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)rn at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)rn at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)rn at java.lang.reflect.Method.invoke(Unknown Source)rnrnrnrnCaused by: org.hibernate.TransientObjectException: object references an unsaved transient instance - save the transient instance before flushing: cn.edu.hust.job.data.entity.Sexrn at org.hibernate.engine.ForeignKeys.getEntityIdentifierIfNotUnsaved(ForeignKeys.java:219)rn at org.hibernate.type.EntityType.getIdentifier(EntityType.java:397)rn at org.hibernate.type.ManyToOneType.isDirty(ManyToOneType.java:242)rn at org.hibernate.type.TypeFactory.findDirty(TypeFactory.java:597)rn at org.hibernate.persister.entity.AbstractEntityPersister.findDirty(AbstractEntityPersister.java:3128)rn at org.hibernate.event.def.DefaultFlushEntityEventListener.dirtyCheck(DefaultFlushEntityEventListener.java:479)rn at org.hibernate.event.def.DefaultFlushEntityEventListener.isUpdateNecessary(DefaultFlushEntityEventListener.java:204)rn at org.hibernate.event.def.DefaultFlushEntityEventListener.onFlushEntity(DefaultFlushEntityEventListener.java:127)rn at org.hibernate.event.def.AbstractFlushingEventListener.flushEntities(AbstractFlushingEventListener.java:196)rn at org.hibernate.event.def.AbstractFlushingEventListener.flushEverythingToExecutions(AbstractFlushingEventListener.java:76)rn at org.hibernate.event.def.DefaultFlushEventListener.onFlush(DefaultFlushEventListener.java:26)rn at org.hibernate.impl.SessionImpl.flush(SessionImpl.java:1000)rn at org.hibernate.impl.SessionImpl.managedFlush(SessionImpl.java:338)rn at org.hibernate.transaction.JDBCTransaction.commit(JDBCTransaction.java:106)rn at org.springframework.orm.hibernate3.HibernateTransactionManager.doCommit(HibernateTransactionManager.java:596)rn ... 88 morernrnrn上面那是这是部分报错信息rnrn[code=Jav]Student student = new Student();rn Sex sex = new Sex();rn sex.setName("nan");rn student.setSex(sex);rn System.out.println("name--------------------"+student.getSex().getName());rn rn student.setStudentNum(sheet.getCell(0, i).getContents().trim());rn StudentType studenttype = new StudentType();rn studenttype.setName(sheet.getCell(1, i).getContents().trim());rn student.setStudentType(studenttype);rn student.setName(sheet.getCell(2, i).getContents().trim());rn student.setExamNum(sheet.getCell(3, i).getContents().trim());rn Department d = new Department();rn d.setName(sheet.getCell(4, i).getContents().trim());rn student.setDepartment(d);rn student.setGraduateTime(new Date(Long.valueOf(sheet.getCell(5, i).getContents().trim())));rn Major m = new Major();rn m.setName(sheet.getCell(6, i).getContents().trim());rn student.setMajor(m);rn Clazz c = new Clazz();rn c.setNumber(sheet.getCell(7, i).getContents().trim().substring(rn sheet.getCell(7, i).getContents().trim().length() - 3,rn sheet.getCell(7, i).getContents().trim().length() - 1));rn student.setClazz(c);rn Cultivate cu = new Cultivate();rn cu.setName(sheet.getCell(8, i).getContents().trim());rn student.setCultivate(cu);rn student.setSchoolingLength(Integer.parseInt(sheet.getCell(9, i).getContents().trim()));rn student.setForeignLanguage(sheet.getCell(10, i).getContents().trim());rn Sex se = new Sex();rn se.setName(sheet.getCell(11, i).getContents().trim());rn student.setSex(se);rn Political p = new Political();rn p.setName(sheet.getCell(12, i).getContents().trim());rn student.setPolitical(p);rn Nation n = new Nation();rn n.setName(sheet.getCell(13, i).getContents().trim());rn student.setNation(n);rn student.setBirthday(new Date(Long.valueOf(sheet.getCell(14,i).getContents().trim())));rn student.setCardId(sheet.getCell(15, i).getContents().trim());rn student.setEnterTime(new Date(Long.valueOf(sheet.getCell(16, i).getContents().trim())));rn Location l = new Location();rn l.setBack_hkqydz(sheet.getCell(17, i).getContents().trim());rn student.setSource(l);rn rn studentService.save(student);[/code]rnrnrn上面这是Java代码,Student 是一个实体对象,Sex ,Major,Clazz ,Department....等等是她的属性,当然也有一些基本数据类型的属性。rn[code=Jav]rn@Entityrn@Table(name = "XS")rnpublic class Student extends User rnrn public PrivilegeRole getPrivilegeRole()rn if(this.isMonitor())rn return PrivilegeRole.MONITOR;rn rn return PrivilegeRole.STUDENT;rn rn rn @Column(name = "XH")rn private String studentNum;// 学号rnrn @Column(name = "KSH")rn private String examNum; // 考生号rnrn @ManyToOne(fetch = FetchType.LAZY)rn @JoinColumn(name = "XLFL")rn private StudentType studentType;rnrn @Column(name = "SFBYS")rn private Boolean graduate = true;// 是否毕业生(判断其能否登陆本系统)rnrn @ManyToOne(fetch = FetchType.LAZY)rn @JoinColumn(name = "YXID")rn private Department department;// 院系rnrn @ManyToOne(fetch = FetchType.LAZY)rn @JoinColumn(name = "ZYID")rn private Major major;// 专业rnrn @ManyToOne(fetch = FetchType.LAZY)rn @JoinColumn(name = "BJ")rn public Clazz clazz;// 班级[/code]rnrn这是实体类的部分代码,有get(),set() 方法,rnrn这样的报错怎么解决?rn之前查了资料说是在注解中使用@ManyToOne(cascade=CascadeType.SAVE_UPDATE,CascadeType.PERSIST)rn可是报了数据类型转换的错误,说CascadeType不能转换为CascadeType ,rnrnrn求助各位大虾了!!!!!!!!!!!!困扰几天了啊啊啊 啊啊啊啊。。。。

Hibernate的一个问题object references an unsaved transient instance-save the transient

02-21

1 我做了一对多和多对一的双向关联关系,在User这一方@ManyToOne已经设置了级联Cascade,这样在测试程序中保存User时,Group也应该自动保存,为什么会抛出以下的异常: (我是按着视频教程里的例子一步一步做的,但视频里却没有异常,是什么原因?)rnrnorg.hibernate.TransientObjectException: object references an unsaved transient instance - save the transient rnrninstance before flushing: com.bjsxt.hibernate.model.Grouprnrn2.如果在测试程序中 HibernateORMappingTest.java:在保存User之前,先把Group也保存了,即加上这一句s.save(g); 就不会出现异常了。可是视频教程里没有这一句,只是设置Cascade级联, 却能通过,这是什么原因呢。rnrnUser.java:rn @Entityrn @Table(name="t_user")rn public class User rn private int id;rn private String name;rn private Group group;rn rn @ManyToOne(cascade=CascadeType.ALL ) //Cascade设置级联rn public Group getGroup() rn return group;rn rn public void setGroup(Group group) rn this.group = group;rn rn @Idrn @GeneratedValuern public int getId() rn return id;rn rn public void setId(int id) rn this.id = id;rn rn public String getName() rn return name;rn rn public void setName(String name) rn this.name = name;rn rn rnrnGroup.javarn @Entityrn @Table(name ="t_group") rn public class Group rn private int id;rn private String name;rn private Set users = new HashSet();rn @Idrn @GeneratedValuern public int getId() rn return id;rn rn public void setId(int id) rn this.id = id;rn rn public String getName() rn return name;rn rn public void setName(String name) rn this.name = name;rn rn rn @OneToMany(mappedBy="group")rn public Set getUsers() rn return users;rn rn public void setUsers(Set users) rn this.users = users;rn rn rnrn测试程序 HibernateORMappingTest.java:rn public class HibernateORMappingTest rnrn private static SessionFactory sessionFactory; rn @BeforeClassrn public static void beforeClass()rn new SchemaExport(new AnnotationConfiguration().configure()).create(false, true);rn sessionFactory= new AnnotationConfiguration().configure().buildSessionFactory();rn rn @AfterClassrn public static void afterClass()rn sessionFactory.close();rn rn @Testrn public void testSaveUser()rn User u = new User();rn u.setName("u1");rn Group g = new Group();rn g.setName("g1");rn u.setGroup(g); rn Session s= sessionFactory.getCurrentSession();rn s.beginTransaction();rn //s.save(g); 加上这一句,就不报错了,可是视频教程里没这一句,只是设置了级联Cascade却能通过rn s.save(u);rn s.getTransaction().commit(); rn rn @Testrn public void testSchemaExport()rn new SchemaExport(new AnnotationConfiguration().configure()).create(false, true);rn rn public static void main(String[] args)rn beforeClass();rn rnrnrn

没有更多推荐了,返回首页