Create a Table for each UML Class

We now want to create a Relational Table for each UML Class in the input model:

  1. Rename the rule myRule to main.
  2. In the body of this rule, type foreach and press Ctrl + Space to invoke the content assist.
  3. Select the foreach - foreach statement code template and press Enter.

  4. Change the code to:
    package tutorial.uml2relational;
    
    public ruleset UML2Relational(in source : uml21, out target : relational) {
    
        public rule main() {
            // create a Table for each Class
            foreach (class : uml21.Class in source.getInstances("Class")) {
                @createTable(class, target.create("Table"));
            }
        }
    
        private rule createTable(class : uml21.Class,
                                 table : relational.Table) {
            // set the name
            table.name = class.name;
        }
    
    }
    
  5. Click File > Save.

Here is the behavior of this ruleset:

  1. Retrieves the list of instances of the type Class in the source UML model, using source.getInstances("Class").
  2. Iterates on this instance list using foreach and the loop variable class of type UML Class.
    1. Creates a Table instance in the target Relational model, using target.create("Table").
    2. Calls the private rule createTable using @createTable(...), passing the class and created Table as arguments.
    3. Sets the name of the table to the same as class (a name attribute is defined on both UML and Relational types).

Notes:

Related concepts
Rule

Related reference
Model APIs
rule call