Search code examples
grailssavefinder

org.springframework.dao.InvalidDataAccessApiUsageException when using grails dynamic finder


Using Grails i'm trying a dynamic finder like this one

Policy.findAllByResourceAndUser(resource,user)

But When i call this, grails raise this exception

Caused by: org.springframework.dao.InvalidDataAccessApiUsageException: object references
an unsaved transient instance - save the transient instance before flushing: gmedia.User;
nested exception is org.hibernate.TransientObjectException: object references an unsaved
transient instance - save the transient instance before flushing: gmedia.User

Do we need to save the parameter of the finder? Where i'm wrong?


Solution

  • http://www.grails.org/DomainClass+Dynamic+Methods#findAllBy*

    Policy.findAllByResourceAndUser(resource,user)

    capital "B" in "By" is the first thing I see wrong? Is that a type on the question?

     def res = new Resource(name:"resource name").save()
     def user = new User(name:"My Name").save()
     def policy = new Policy( user:user, resource:res, right: "right string").save()
    
     println Policy.findAllByResourceAndUser(res,user)
    

    not elegant, but you get the idea, there must be a problem in the way you are saving your objects

    your user object will "never" get saved with that code... you have to specify values for all of you properties or define your constraints appropriately. I think you should review the documentation for Domain Objects in Grails because it appears there are fundamental problems in your approach see http://www.grails.org/GORM+-+Creating+a+domain+class