13

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?

3
  • What is the Grails version used? I have used Grails 2.4.4 and used the domain classes provided by you i.e. Assessment, Benefit, Income and IncomeSource. It has not created extra join table as you have mentioned. And it has added assessment_id in benefit, income, and income_source tables. So it would be easy to verify if you provide the Grails version used by you for this examples.
    – Ramsharan
    May 25, 2015 at 15:55
  • I'm using Grails 2.5.0
    – Dónal
    May 26, 2015 at 22:44
  • Did it work as shown in the answer?
    – dmahapatro
    Jun 2, 2015 at 13:51

1 Answer 1

1

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.