06 - GORM: Page 2 of 2

Many to Many Relations

When you have a relation between different entities where for instance, entity1 can have multiple instances of entity2, and entity2 can have multiple instances of entity1, then this is a many to many relationship. In grails we need to define an additional entity that will handle these linked entities.

Let’s create a new domain-class called Service, which will identify a service to which the Subscriber can register to and also create a domain-class called Registration, which will be used to store the registration of a Subscriber to a specific service.

                    

Let’s keep it simple, so our Service entity will only have a description as:

package tutorialdemo
class Service {
    String description
    static constraints = {
    }
    static hasMany = [registrations:Registration]
    String toString(){
        return "${description}"
    }
}

And let’s create the Registration entity:

                    

package tutorialdemo
class Registration {
    Date dateCreated
    static constraints = {
    }
    static belongsTo = [subscriber:Subscriber, service:Service]
}

And finally, let’s update the Subscriber entity to show that it also can have many registrations. Change the line for the hasMany to this:

       static hasMany = [profiles:Profile, registrations:Registration]

package tutorialdemo
class Subscriber {
    String name
    String lastName
    String status
    static constraints = {
    }
    static hasMany = [profiles:Profile, registrations:Registration]
    String toString(){
        return "${lastName}, ${name}"
    }
}

Now, let’s create two more controllers for Services and Registration:

                    

package tutorialdemo
class RegistrationController {
    def scaffold=true
}

                

package tutorialdemo

class RegistrationController {

     def scaffold=true
}

 

Now, let’s run our application and create several subscribers:

          

And create several services:

          

And now let’s go to the registration and we can now see that we can create new records for multiple subscribers and multiple services.

          

          

So this concludes our tutorial about Grails. I hope you find it helpful.

 

Like us on Facebook