问题
I have a class hirarchy :
class Item {}
class Participation extends Item{}
class Contribution extends Participation{}
class Question extends Participation{}
I would like to have a table per class so, I add tablePerHierarchy false in Item
I need a discrimator to implements a query : where class = "Contribution"
I try a lot of implementation but it's not working.
How to do that ?
Thanks
回答1:
Do you want table per hierarchy or table per class? It's not clear in your question.
With the following domain objects, you can do it either way:
// Item.groovy
class Item {
String x
}
// Participation.groovy
class Participation extends Item {
String y
}
Using the default, table per hierarchy strategy, just one table will be used to store Items and all the subclasses of Items too. The default discriminator column is called class, which grails will use automatically. The schema generated by grails schema-export looks like this:
create table item (
id bigint generated by default as identity (start with 1),
version bigint not null,
x varchar(255) not null,
class varchar(255) not null,
y varchar(255),
primary key (id)
);
There's just one table for both classes which contains all the fields declared in every class in the hierarchy plus the discriminator column class. If you do a query like Participation.list(), the SQL grails generates looks like this:
select
this_.id as id1_0_,
this_.version as version1_0_,
this_.x as x1_0_,
this_.y as y1_0_
from
item this_
where
this_.class='Participation'
By changing the inheritance strategy to table per class with static mapping { tablePerHieracrchy false } in Item.groovy, grails will generate a table for each of classes in the hierarchy. Each table stores only the fields declared in each class, so a Participation object would be represented by a row in both the Item table and the Participation table. The schema looks like this:
create table item (
id bigint generated by default as identity (start with 1),
version bigint not null,
x varchar(255) not null,
primary key (id)
);
create table participation (
id bigint not null,
y varchar(255) not null,
primary key (id)
);
And the SQL for Participation.list() changes to:
select
this_.id as id1_0_,
this_1_.version as version1_0_,
this_1_.x as x1_0_,
this_.y as y2_0_
from
participation this_
inner join
item this_1_
on this_.id=this_1_.id
来源:https://stackoverflow.com/questions/5192375/how-to-implements-tableperhierarchy-with-disciminator-in-grails