Hello I have two domain classes as following
class Users {
String password
String firstName
String lastName
String emailAddress
String username
Company company
.....
static hasMany = [projects:Projects];
}
Another class
class Projects {
String projectName
String description
Users projectLead
Date dateCreated
Date lastUpdated
static belongsTo = Users
}
These classes obviously has one to many relationship but now I want to change it to many to many relationship by adding “ProjectMembership” class but the problem I have is that my application has already gone into production and there are people who are already using the app. In such a case they already have one user->many projects in the the db. In such a case how can I migrate this existing data and change my prod app to have m2m relationship which will looks like following.
class Users {
String password
String firstName
String lastName
String emailAddress
String username
Company company
.....
static hasMany = [projectMemberships:ProjectMemberships];
}
Another class
class Projects {
String projectName
String description
Users projectLead
Date dateCreated
Date lastUpdated
static hasMany = [projectMemberships:ProjectMemberships];
}
and
class ProjectMemberships{
Users u
Projects p
}
This is best done with a migration tool like Liquibase, and the http://grails.org/plugin/database-migration plugin is probably your best be in Grails since it uses Liquibase and is tightly integrated with GORM. But this one’s easy enough to do by hand.
I wouldn’t use
hasManysince you can easily manage everything from theProjectMembershipsclass, so yourUsersandProjectsclasses would beand
I’d go with a
ProjectMembershipsclass that uses a composite key, which requires that it implementSerializableand have a goodhashCodeandequals:Use
ProjectMemberships.create()to add a relationship between a user and a project, andProjectMemberships.remove()to remove it.Run
grails schema-exportto see the updated DDL (it’ll be intarget/ddl.sql). Run the create table statement for theproject_membershipstable, e.g.Then populate it with this SQL (depending on your database you might need a slightly different syntax):
and finally drop the
project_lead_idcolumn from theprojectstable.Of course do a database backup before making any changes.
You can get a user’s projects with
and similarly a project’s users with