Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

inheritance in Grails domain model causes duplicate foreign keys

In the domain model of my Grails 2.5.0 app I have two classes Income and Benefit that have identical properties. I would like to store these in separate database tables, but move the common fields into a base class. The model I've come up with is:

class Assessment {

    Date dateCreated = new Date()
    User user

    static hasMany = [incomes: Income, benefits: Benefit]
}

class Benefit extends IncomeSource {}

class Income extends IncomeSource {}

abstract class IncomeSource {

    String name
    BigDecimal amount
    PaymentFrequency frequency

    static belongsTo = [assessment: Assessment]

    static mapping = {
        tablePerHierarchy false
    }
}

This causes the following tables to be generated for the relationship between Assessment and Benefit

enter image description here

The tables created for the the relationship between Assessment and Benefit are (unsurprisingly) identical.

Rather than having an assessment_benefit join table between assessment and benefit, I would prefer to have an assessment_id foreign key in the benefit table, thereby eliminating the need for the join table.

How can I change my domain model to achieve this?

like image 244
Dónal Avatar asked May 21 '15 19:05

Dónal


1 Answers

How can I change my domain model to achieve this?

Move

static belongsTo = [assessment: Assessment]

from abstract parent IncomeSource to child Benefit as:

class Benefit extends IncomeSource {
    static belongsTo = [assessment: Assessment]
}

You can also keep this relation in the base class and just copy belongsTo to child as well.

No join table will be created for Assessment and Benefit in either case.

Same would be applicable for Income, if similar behavior is required.

Applicable for Grails 2.5.0

like image 109
dmahapatro Avatar answered Oct 02 '22 20:10

dmahapatro