Search code examples
grailsgrails-ormgrails-plugingrails-domain-classgrails-controller

Grails - Multiple Tables in Single Domain Class


I have two tables with a common primary key. Now i want to get data from that both tables and show in single view using that primary key.

How i can get both table data in single domain class? How can i specify mapping?

For Example

Table-A and Table-B both are in single schema ABC

class X {
   int id
   String name

   static mapping = {
      table name: "Table-A", schema: "ABC"
      columns {
         name column:'name'
      }
   }
}

now i want to get address from table-B so that my view looks like below

ID  NAME  ADDRESS
2   HSJHD  23 X-Street Washington USA

How to get two table data in single domain class?


Solution

  • This sounds like a foreign key relation, you would simply use belongsTo in each object (provided a one-to-one relationship). http://grails.org/doc/latest/ref/Domain%20Classes/belongsTo.html

    Otherwise you could create a database view on your database, then create a domain object to match that view. Creating a domain based on a database view is identical to creating a domain based on a table.