As we know that implementation of many to many in sql is difficult because it needs a third table for maintaining relation. But it is easy in MongoDB , I will show you steps how to implement many to many relation in Grails with MongoDB
In a project, I had to implement many to many relation between two domains named as User and Circle. Scenario is that user has many circles and each circle has many user.
I assume that you have configured mongodb plugin in grails application and created database in mongodb.
Steps for implement many to many relation
Create two domain using following commands
grails create-domain-class User
grails create-domain-class Circle
Add data members and mapping
In User
String name;
List<Circle> circles
static mapWith = "mongo"
static hasMany=[circles:Circle]
In Circle
String name;
List<User> users;
static mapWith = "mongo"
static belongsTo=User //This line is used to make user as owner
static hasMany=[users:User]
After saving some documents in above domains you will see these domain like following manner in mongodb.
More From Oodles
Ready to innovate? Let's get in touch
Cookies are important to the proper functioning of a site. To improve your experience, we use cookies to remember log-in details and provide secure log-in, collect statistics to optimize site functionality, and deliver content tailored to your interests. Click Agree and Proceed to accept cookies and go directly to the site or click on View Cookie Settings to see detailed descriptions of the types of cookies and choose whether to accept certain cookies while on the site.
About Author
Shivam Gupta
Shivam is a bright java developer with experience in building enterprise applications using Flex and Java. He is also well versed with Groovy and Grails development.