简体   繁体   中英

Grails - not-null property references a null or transient value

I have a few basic grails domain objects:

Task User

Recently, I wanted to be able to assign tasks to multiple Users. So I added this code to the Task.groovy class:

static hasMany = [users: User]

static mapping = {
    users joinTable: [name: 'task_user', column: 'user_id', key: 'task_id']
}

So a Task can now be assigned to multiple users using a join table - joining Task and User tables. Now when I create a new Task, it's giving me the error message:

"not-null property references a null or transient value: blah.User.address"

In the generated join table "task_user" it only needs the user_id from the User object so I don't understand why it's complaining that other user fields are null. The user object will always be present in the database. I don't want to have to fully load each user in order to create a new Task. I'm pretty sure it has something to do with cascading.

I want the behavior where if a Task is deleted, the associated entry in the task_user join table should be deleted. I "never" want the User object updated/deleted as a result of saving a Task. I'm not sure how to proceed.

Fix

You need to use User.load(id) to get a reference to an user object. load unlike get doesn't hit the database - it just creates a proxy which can be used in place of the User object. As long as only the id property is accessed - db is not accessed.

Explanation for the error you are seeing

In your code you created a new user object (transient) which is not connected to hibernate. To get it connected to hibernate you either need to save it or add the belongs_to attribute - both of these will try to update the row in the user table with every field set to null. If it was a new user object you were creating and wanted it to be saved automatically you would need to set the belongs_to (~ to cascade).

Have you modified the constraints on the User table recently? I've seen those errors before, usually when I make a property not nullable after the schema's already been generated... I'm guessing if there's a null value already in the table for a property that's modified to be not-nullable the schema-update fails silently and you end up with errors like this.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM