Grails Gorm : Object references an unsaved transient instance

北战南征 提交于 2019-12-04 03:31:48

问题


I get the following Exception when saving an instance of Trip in Grails:

2011-01-26 22:37:42,801 [http-8090-5] ERROR errors.GrailsExceptionResolver - object references an unsaved transient instance - save the transient instance before flushing: Rower org.hibernate.TransientObjectException: object references an unsaved transient instance - save the transient instance before flushing: Rower

The concept is simple: For a boattrip you need some rowers, a coxwain (is also a rower) and a boat:

Trip looks like (shortened):

class Trip {
    Boat boat;
    Rower coxwain;

    static belongsTo = [Rower,Boat]
    static hasMany = [rowers:Rower]
}

and Rower (shortened)

class Rower { 
    String firstname;
    String name;
    Rower reference;

    static hasMany = [trips:Trip];
    static mappedBy = [trips:"rowers"]
}

The trip then is saved in the controller like:

def save = {
        def trip = new Trip(params)

        // adding Rowers to Trip
        if (params.rower instanceof String) {
            def r = Rower.get(params?.rower)

            if (r != null) {
                trip.addToRowers(r)
            }
        } else {
            params?.rower?.each{
                rowerid ->
                def r = Rower.get(rowerid)
                log.info("rowerid (asList): " + rowerid)
                if (r != null) {
                    trip.addToRowers(r)
                }
            }
        } 

        // saving the new Trip -> EXCEPTION IN NEXT LINE
        if(!trip.hasErrors() && trip.save(flush:true)) {
          // ...
        }
        // ...
}

I think I have set the relations between the domains correct. The Rower is not changed while it is added to the Trip. Why does Grails want it to save? why is it a transient instance?


回答1:


Unfortunately this is an issue with the way GORM handles things, or more specifically the way that it expects that you deal with transients. If you don't persist the contained classes to the database first (Rowers in this case), you will get this exception every single time.

With GORM you have to save and attach in a bottom up fashion or when grails goes to flush the connection for the next instance you will get the transient instance exception. The instance is 'transient' because its just an in-memory reference. To persist the parent, GORM needs to link the parent to the child in the database. Without the child being persisted it has no way to do that, this is where the exception is coming from.

Wish there was better news. Not that its hard, but it gets annoying with complex hierarchies.




回答2:


The Problem was somehow different. it's in here:

def trip = new Trip(params)

which references a coxwain (of class Rower), which is not set (id=-1 is returned). This constructs a new Rower instead of a 'null' value. And this is the 'unsaved transient instance'. If I check first for a valid instance, then it works :-)

Thanks for the help!




回答3:


Just a quick note for anyone dealing with singular or multiple parameters with the same name, using the params.list("parameterName") helper you can always return a list

    ...

    // adding Rowers to Trip
    if (params.rower instanceof String) {
        def r = Rower.get(params?.rower)

        if (r != null) {
            trip.addToRowers(r)
        }
    } else {
        params?.rower?.each{
            rowerid ->
            def r = Rower.get(rowerid)
            log.info("rowerid (asList): " + rowerid)
            if (r != null) {
                trip.addToRowers(r)
            }
        }
    } 

    ...

could become a bit groovier

    ...

    // adding Rowers to Trip
    for(rower in params.list("rower") {
        def r = Rower.get(rower) 
        if(r) trip.addToRowers(r)
    } 

    ...

you can find it hiding away under 6.1.12 Simple Type Converters




回答4:


At first I thought it was to do with cascading saves and belongsTo, as described in The Grails Reference section 5.2.1.3 and Gorm Gotchas part 2. However since the Rowers are already in the DB I think it should work. The domain model is complicated to me, what you need to do is simplify it and run some tests using Grails console (run grails console in your project directory). First create a basic many-to-many between Trip and Rower and get it to execute the desired code. Then add the other parts bit-by-bit, like Rower's reference to itself. I'm not sure that the mappedBy part is necessary at all.




回答5:


I think you have to save the trip before you add the rover to the trip. Also it make no sense to check if trip has errors before you validate and/or save it.

Try this:

if(trip.validate() && trip.save(flush:true)) {
    if (r != null) {
       trip.addToRowers(r)
    }  
}



回答6:


In many use cases, you should be able to address this by applying the cascade setting to your collection:

static mapping = {
    rowers cascade: 'all-delete-orphan'
}

https://docs.grails.org/latest/ref/Database%20Mapping/cascade.html




回答7:


Suppose, you are using Trip is hasMany relationship with Rower

class Trip {
      static hasMany = [rowers:Rower]
      ...
    }

class Rower{
      static belongsTo =[trips:Trip]
      ...
   }

Actually, it's looking for new session. So we need to stop/rollback the current transaction then this error won't raise, For that Try This,

  def row = new Row()
  row.save()

NOTE: this save won't affect your database. It's just for rollback the transaction.



来源:https://stackoverflow.com/questions/4810574/grails-gorm-object-references-an-unsaved-transient-instance

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!