Search code examples
grailsgrails-ormgrails-domain-class

Domain design to store user's country, age group, etc


Here is the situation: a user table contains data that overlap with other users' data such as country, age group, gender, etc.

In MySQL, I would use three tables or two. In the case storing country, I would use three tables: one would the be user table, the other country table, and the last one that joins the two. (Of course I could use two tables if one user has one country.)

ex) user(id, otherUserInfo), userCountry(id_user, id_country), country(id, countryName)

Being new to Grails, I was wondering what's the best way to represent this schema. Is it necessary to create 2-3 domain classes? Or is there some magical feature (like so many other Grails features (: ) to do this in a single domain class.


Solution

  • More than likely you could do it with two.

    class User {
        //other user info
    
        //if user only has one country
        Country country
    
        //if user has many countries
        static hasMany = [countries: Country]
    }
    
    class Country {
        //country info
    }
    

    Since you probably don't want a Country to belong to the User, you don't need anything in the Country class to indicate ties back to the User. Grails/Gorm will handle creating the linking entities in either of these cases.

    If the user has many countries and you needed to store other information regarding the relationship you would need to create your own join table. For example if you needed to keep the number of visits the user has made to the country:

    class User {
         //other user info
    
        static hasMany = [userCountries: UserCountry]
    }
    
    class UserCountry {
        static belongsTo = [user: User]
        Country country
        int numberOfVisits
    }
    
    class Country {
        //country info
    }