好吧,我会简化问题,以便您更好地理解它。
我有一个正在制作的软件,其中包含一个名为Person
的域,其中包含一些属性。
我在Contact
域中添加了一个名为Person
的新属性,当我启动应用程序从Contact
获取一些信息时,需要更新Person.AnotherContactObject
。
所以在Bootstrap.groovy
我尝试这样做:
List<Person> persons = Person.findAll()
for(Person person : persons){
person.contact = new Contact()
person.save(flush:true)
}
我收到了这个错误:
context.GrailsContextLoader Error initializing the application: object references an unsaved transient instance - save the transient instance before flushing: com.test.Contact; nested exception is org.hibernate.TransientObjectException: object references an unsaved transient instance - save the transient instance before flushing: com.test.Contact
org.springframework.dao.InvalidDataAccessApiUsageException: object references an unsaved transient instance - save the transient instance before flushing: com.test.Contact; nested exception is org.hibernate.TransientObjectException: object references an unsaved transient instance - save the transient instance before flushing: com.test.Contact
at BootStrap$_closure1.doCall(BootStrap.groovy:154)
at grails.util.Environment.evaluateEnvironmentSpecificBlock(Environment.java:308)
at grails.util.Environment.executeForEnvironment(Environment.java:301)
at grails.util.Environment.executeForCurrentEnvironment(Environment.java:277)
at java.util.concurrent.FutureTask.run(FutureTask.java:262)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
at java.lang.Thread.run(Thread.java:745)
Caused by: org.hibernate.TransientObjectException: object references an unsaved transient instance - save the transient instance before flushing: com.test.Contact
... 8 more
好吧,我也尝试过这样解决方法:
创建新的Contact
对象,将其保存,然后在person.contact
中设置并保存person
对象,但仍然存在相同的错误。
答案 0 :(得分:0)
我假设Contact
也是一个域类。您需要先保存Contact
,然后才能保存Person
。
List<Person> persons = Person.findAll().each { person ->
person.contact = new Contact().save(flush:true)
person.save(flush:true)
}
当然,在保存之前不要忘记在Contact
实例中设置所有不可为空的属性。