Search code examples
grailstreegrails-ormone-to-manylegacy

Grails GORM: Mapping tree legacy table


I'm currently trying to map a legacy (mysql) table with the following 3 relevant fields:

id -> Long
parentId -> Long
title -> String

id and parentId describe the tree-structure. What I need is a method to search all nodes under a given one for a certain title and retrieve that node's id. I am new to Grails and can't get my head around mapping that one-to-many relationship based on an existing table.


Solution

  • To map the class, try something like this:

    class Foo {
    
        String title
        Foo parent
    
        static mapping = {
            parent column: 'parentId'
        }
    }
    

    You don't need to specify the id as a Long because that is the default. You will, however, need to specify the id if it has a column name other than id.

    As far as the parent object goes, you will need to map it by the foreign key column's name.