如何在grails中使用disciminator实现tablePerHierarchy?

Jon*_*run 2 grails grails-orm

我有一个课堂hirarchy:

class Item {}
class Participation extends Item{}
class Contribution extends Participation{}
class Question extends Participation{}
Run Code Online (Sandbox Code Playgroud)

我希望每个类都有一个表,所以我在Item中添加了tablePerHierarchy false

我需要一个discrimator来实现一个查询:where class ="Contribution"

我尝试了很多实现,但它不起作用.

怎么做 ?

谢谢

ata*_*lor 6

您是否希望每个类的每个层次结构或表有表?你的问题不清楚.

使用以下域对象,您可以这样做:

// Item.groovy
class Item {
    String x
}

// Participation.groovy
class Participation extends Item {                   
     String y
}
Run Code Online (Sandbox Code Playgroud)

使用默认的每层次结构表策略,只有一个表用于存储Items和Items的所有子类.调用默认的鉴别器列class,grails将自动使用.生成的模式grails schema-export如下所示:

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)
);
Run Code Online (Sandbox Code Playgroud)

这两个类只有一个表,它包含层次结构中每个类中声明的所有字段以及鉴别器列class.如果您执行类似的查询Participation.list(),则SQL grails生成如下所示:

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'
Run Code Online (Sandbox Code Playgroud)

通过static mapping { tablePerHieracrchy false }在Item.groovy 中将继承策略更改为每个类的表,grails将为层次结构中的每个类生成一个表.每个表仅存储在每个类中声明的字段,因此Participation对象将由Item表和Participation表中的一行表示.架构如下所示:

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)
);
Run Code Online (Sandbox Code Playgroud)

并将SQL Participation.list()更改为:

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
Run Code Online (Sandbox Code Playgroud)