Search code examples
grailsgrails-orm

Grails How to save data in a table with belongsTo association?


I have two model classes: User and Balance.

class User {

Balance balance
String name
String role
String password
static constraints = { }
}


class Balance {

double balance
static belongsTo = [user:User]
static constraints = {}
}

Every balance belongs to a user. Now, I need to save user and balance details in their respective tables using saveAdd() function.

 def saveAdd(){
    def name = params.name
    def password= params.password
    def balance = Double.parseDouble(params.balance)
    def u = new User(name:name,password:password,role:"user", balance: new Balance(balance:balance))
    u.save(flush:true)
}

But I get "java.lang.reflect.InvocationTargetException: null" error. Is there any mistake in the mapping process? What am I missing?


Solution

  • I would reorganize the code so:

    class User {   
      static hasOne = [ balance:Balance ]
    }
    
    class Balance {
      static belongsTo = [user:User]
    }
    

    then you should have no problems saving the objects in your controller:

     def saveAdd(){
        def u = new User(...)
        def b = new Balance(user:u, ...)
        b.save()
        u.save(flush:true)
    }