I am following the example in Grails in Action. I have an issue understanding how the addTo*()
function works.
I have a simple domain: User, Post, Tag with the following relationships:
When I run the following code (first case):
1. def user = new User(userId: 'joe', password: 'secret').save()
2. def tagGroovy = new Tag(name: 'groovy')
3. def tagGrails = new Tag(name: 'grails')
4. user.addToTags(tagGroovy)
5. user.addToTags(tagGrails)
6.
7. def groovyPost = new Post(content: 'A groovy post')
8. user.addToPosts(groovyPost)
9. groovyPost.addToTags(tagGroovy)
10.
11. User.get(1).tags.each {println it.id + " " + it.name}
12. User.get(1).posts.each {println it.id + " " + it.content + " " + it.dateCreated}
I get this:
null grails
null groovy
null A groovy post null
And if I change lines 4, 5, and 8 to:
4. user.addToTags(tagGroovy).save(flush: true)
5. user.addToTags(tagGrails).save(flush: true)
8. user.addToPosts(groovyPost).save(flush: true)
I get this:
2 grails
1 groovy
1 A groovy post Tue Nov 22 21:00:00 WET 2011
Can someone explain why in the first case the id
and dateCreated
properties are not persisted?
It's really a hibernate issue.
The entire object graph gets saved only when you save your user object. So they are associated with the user but not yet persisted in the database, so they have no ids.
In your example, if you add User.save( flush: true ) before your get(1) lines, you will see that all the new posts get persisted in the database.
Peter Ledbrook explains it a little better in this post - http://blog.springsource.org/2010/06/23/gorm-gotchas-part-1/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With