代码之家  ›  专栏  ›  技术社区  ›  Philippe

使用gorm dsl将多个域对象映射到同一个表

  •  3
  • Philippe  · 技术社区  · 14 年前

    我正在一个遗留数据库上创建一个Grails应用程序。
    有一个表,我想从中创建几个不同的域对象(下面的示例中是type1、type2和type3)。
    桌子是这样的:

    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
    ...
    

    所以我想创建3个不同的域类,每个类包含一个名为“description”的字段,并对应一个特定的“type”,因为这些行代表不同的概念。

    是否有任何类型的约束允许我按类型筛选行?

    我是说,我能做点什么吗?

    class Type1 {
        String type
        String description
    
        static mapping = {
           table 'mytable'
        }
    
        static constraints = { type == 'type1' } // Is there anything like this ?
    
     }
    

    然后,我希望type1.list()生成一个如下的查询:

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

    更新:

    实际上, documentation 说我可以用鉴别器来实现这一点。

    但是,我试图将我的课程设置为:

    class Type1 extends BaseType {
    
      static mapping = {
        discriminator column:'type', value: 'type1'
      }
    
    }
    

    我激活了Hibernate SQL跟踪,而不是看到

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

    我懂了

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

    似乎鉴别器完全忽略了我的自定义列名:-(

    我用的是Grails 1.2.1

    2 回复  |  直到 14 年前
        1
  •  5
  •   Philippe    14 年前

    所以Grails文档不是最新的( it should though )

    解决方案是:

    在BaseType类中:

    static mapping = { discriminator column:"type" }
    

    在子类中:

    static mapping = { discriminator value:"type1" } // or type2, type3, etc...
    
        2
  •  0
  •   tim_yates    14 年前

    The GORM Documentation 似乎建议你可以,只要你所有的typex类都扩展一个公共的基类