Reputation: 575
I have 3 domain classes User, Server, Quota and I want to map them with the following relations
Upvotes: 0
Views: 98
Reputation: 3122
You can create a NxN relation between User and Server. However, will be necessary create a class for that relation. This is necessary because you need the attribute quota. In the standard way of a NxN relation Grails (Hibernate) doesn't create a class for it.
You'll need three classes:
User,Server,UserServer
Class UserServer {
int quota
static belongsTo = [user:User, server:Server]
static constraints = {user unique: 'server'}
}
The unique constraint it's very important, because as you said, a User may have exactly one entry for each Server.
To link and unlink a User and Server you can use the following methods:
Class UserServer {
int quota
static belongsTo = [user:User, server:Server]
static constraints = {user unique: 'server'}
static PackScheme link(User user, Server server) {
UserServer userServer = UserServer.findByUserAndServer(user, server)
if (!userServer) {
userServer = new UserServer()
user.addToUserServers(userServer)
server.addToUserServers(userServer)
userServer.save()
}
return userServer
}
static void unlink(User user, Server server) {
UserServer userServer = UserServer.findByUserAndServer(user, server)
if (userServer) {
user.removeFromUserServers(userServer)
server.removeFromUserServers(userServer)
userServer.delete()
}
}
}
Note that you need to create a hasMany relation in User and Server called userServers:UserServer.
This solution is based on this link: http://grails.org/Many-to-Many+Mapping+without+Hibernate+XML
Upvotes: 1