Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Grails addTo* clarification

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:

  • User 1-to-M Post
  • User 1-to-M Tag
  • Post M-to-M Tag

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?

like image 987
Yassine Elouri Avatar asked Nov 22 '11 21:11

Yassine Elouri


1 Answers

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/

like image 171
Tomas Lin Avatar answered Sep 29 '22 17:09

Tomas Lin