views:

236

answers:

2

Hi, 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

A: 

The GORM Documentation seems to suggest you can, so long as all your TypeX classes extend a common base class

tim_yates
Yeah I am trying that... but my table doesn't have a 'class' column... I'll try to map the TYPE column to the "class" discriminator and see if that works...
Philippe
+3  A: 

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...
Philippe
Cool bit of detective work there :)
tim_yates