gvnixgvnix-es

Many to many relation in GvNIX


In my E-R model I have two classes (User and Routine) related by many to many relationship, but I don't know how to translate it to GvNIX code. Should I use a set attribute in each class specifying a many to many cardinality? For example:

field set --fieldName routines --class ~.objects.User --type ~.objects.Routine --cardinality MANY_TO_MANY 
field set --fieldName users --class ~.objects.Routine --type ~.objects.User --cardinality MANY_TO_MANY

Solution

  • To map a many-to-many relationship in both directions, one direction must be defined as the owner and the other must use the --mappedBy attribute to define its mapping.

    Taking the typical Employee-Project example, one Employee can participate in many Projects and one Project can have many Employees. To create such bi-directional many-to-many relationships use the field set command:

    Create the entities:

    entity jpa --class ~.domain.Project
    entity jpa --class ~.domain.Employee
    

    Create the owner of the relationship:

    field set --class ~.domain.Employee --fieldName projects --type ~.domain.Project
    

    Then create the other side of the relationship:

    field set --class ~.domain.Project --fieldName employees --type ~.domain.Employee --mappedBy projects
    

    If the --mappedBy is not used, then the persistence provider will assume there are two independent relationships, and you will end up getting duplicate rows inserted into the join table. If you have a conceptual bi-directional relationship, but have two different join tables in the database, then you must not use the --mappedBy, as you need to maintain two independent tables.

    Finally, to customize the generated code just use the JPA force Luke, take a look at http://en.wikibooks.org/wiki/Java_Persistence/ManyToMany