Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mapping multiple domain objects to the same table using GORM DSL

I'm creating a grails app over a legacy database.
There is a table out of which I would like to create several different domain objects (Type1, Type2 and Type3 in my example below).
The table is like this :

ID    TYPE    DESCRIPTION
1     type1   description of a type1 object
2     type1   description of another type1 object
3     type2   description of a type2 object
4     type3   description of a type3 object
...

So I would like to create 3 different domain classes, each containing a field named "description", and corresponding to a specific "type", because the rows represent different concepts.

Is there any kind of constraint that allows me to filter the rows by type ?

I mean, could I do something like :

class Type1 {
    String type
    String description

    static mapping = {
       table 'mytable'
    }

    static constraints = { type == 'type1' } // Is there anything like this ?

 }

Then I would expect Type1.list() to produce a query like :

SELECT type, description 
FROM mytable
WHERE type = 'type1'

Update :

Actually the documentation says that I can use a discriminator to achieve this.

However, I tried to set my class as follows :

class Type1 extends BaseType {

  static mapping = {
    discriminator column:'type', value: 'type1'
  }

}

I activated hibernate SQL tracing, and instead of seeing

SELECT ... FROM mytable WHERE type = 'type1'

I see

SELECT ... FROM mytable WHERE class = 'type1'

It seems the discriminator is completely ignoring my custom column name :-(

I'm using Grails 1.2.1

like image 862
Philippe Avatar asked Jan 29 '26 17:01

Philippe


1 Answers

Ok so the Grails documentation is not up to date (it should though).

The solution is :

In the BaseType class :

static mapping = { discriminator column:"type" }

In the subclasses :

static mapping = { discriminator value:"type1" } // or type2, type3, etc...
like image 103
Philippe Avatar answered Feb 01 '26 11:02

Philippe



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!