Question

I'm facing a issue regarding inheritance in Grails. I have a domain class Person.grooy:

class Person{
    String name
    String contactNumber
    Address address
} 

Now I'm extending Person.groovy for Employee and Customer like:

class Employee extends Person{
    String designation
}
class Customer extends Person{
    String interest
}

Now I want separate table in my database for Employee and Customer having columns of Person i.e name,contactNumber and associate address key. How could I achieve this. I searched every where but there is nothing for this aspect. Is this one approach is not possible in GORM. Please answer. Thanks Guys

Was it helpful?

Solution

Finally I managed to get what I want just by placing a grails.persistence.Entity annotation to my child domain classes. I also make my parent i.e. Person.groovy abstract and place in src/groovy.

Now I have database hierarchy as I expected but some scaffold issues in controller still persist that will also sorted out with your help.

OTHER TIPS

You need to disable table-per-hierarchy, which is by default enabled in Grails

class Employee extends Person{
    String designation

static mapping = {
        tablePerHierarchy false
    }
}

table-per-hierarchy Ref

If you put your Person class in src/java or src/groovy it won't be mapped to the db.

Remember to import it into your Employee and Customer classes

import com.yourPackage.Person

class Employee extends Person{

}

It looks like inheritance is not the approach we need to follow here. You should create composition with Person class and it will store the properties of Person class in Employee.

class Employee {
    Person person
    String designation

    static embedded = ['person']
}

Gorm Composition

you can put it inside src/java, but that solution will not be standard, as it really will not be treated as a grails domain example once you get deeper into the application.

For example, if you want to create a controller or a test script on the extended domain as per the previous answer, it will be complicated.

As of grails 2.2.x I believe, grails provides you with mapWith. You can use that for a more maintainable solution

class Employee{
static mapWith = "none"
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top