Java Reference
In-Depth Information
In Listing 7-31 there is a unidirectional one-to-many. Grails will, by default, map this kind of relationship
with a join table. Grails will automatically inject a property of type java.util.Set into the domain class
based on the hasMany setting. Grails supports many-to-many relationships by defining a hasMany on
both sides of the relationship and having a belongsTo on the owned side of the relationship.
You will create an application with a many-to-many domain relationship between Author and Book .
You can find the source code for this application in the books project in Chapter 7 of the source
code archive that you can download from the Apress website. Listing 7-32 illustrates the Book class.
Listing 7-32. Creating a Domain Relationship Between Book and Author
1.package books
2.
3.class Book {
4. static belongsTo = Author
5. static hasMany = [authors:Author]
6. String title
7.Long isbn
8.String publisher
9.static constraints = {
10.title(blank:false)
11.}
12.
13.String toString() {
14.title
15.}
16.}
Line 4 : This line informs Grails that the Book class belongs to its owning Author .
Line 5 : This line inform Grails that the Book class has many instances of Author .
Listing 7-33 illustrates the Author class.
Listing 7-33. Author class.
1.package books
2.
3.class Author {
4.
5. static hasMany = [books:Book]
6. String firstName
7.String lastName
8.static constraints = {
9.firstName(blank:false)
10.lastName(blank:false)
11.}
12.String toString() {
13."$lastName, $firstName"
14.}
15.}
Line 5 : This line tells Grails that an Author has many instances of Book .
 
Search WWH ::




Custom Search