【问题标题】:How to "inherit" constraints from trait?如何从特征“继承”约束?
【发布时间】:2019-08-20 11:13:47
【问题描述】:

我有一个特征和以下领域类:

trait Named {

  String name

  static constraints = {
    name blank:false, unique:true
  }
}

@Entity
class Person implements Named {

  String fullName

  static constraints = {
    fullName nullable:true
  }

}

@Entity
class Category implements Named {

}

在此设置中,Named.constraints 对于 Category 工作正常,但对于 Person 会被忽略。

如何在实现域类的constraints 块中包含来自特征的约束?

【问题讨论】:

    标签: grails groovy constraints grails-orm traits


    【解决方案1】:

    如何在约束块中包含来自特征的约束 实现领域类?

    框架不支持。

    【讨论】:

    • 约束继承是否适用于正确的类继承(无特征)?
    • @injecteer 不是隐含的,但请参阅stackoverflow.com/a/24978696/3181392 - 想知道这是否也适用于特征
    • @cfrick 仅供参考...您链接到的帖子中提到的解决方案的某些方面将不起作用。例如,bindable 在某些情况下会出现问题。
    • @cfrick 你觉得我的回答怎么样?
    • @injecteer 我知道你问的是 cfrick 而不是我,但请注意,约束的编译时间处理对于这种方法来说是有问题的。有些事情会奏效。并非所有人都会。
    【解决方案2】:

    我找到了重用约束最不痛苦的方法。

    我添加了一个新类:

    class CommonConstraints {
    
      static name = {
        name blank:false, unique:true
      }
    }
    

    然后,我没有使用无效的importFrom Named,而是撒了一些时髦的魔法:

    @Entity
    class Person implements Named {
    
      String imgUrl
    
      String fullName
    
      static constraints = {
        CommonConstraints.name.delegate = delegate
        CommonConstraints.name()
        fullName blank:false, unique:true
        imgUrl url:true
      }
    
    }
    

    而且它的作用就像魅力。

    是的,该解决方案与继承/实现模型不一致,但完成了代码重用工作。

    对于不太棘手的情况,域类没有自己的约束,将使用来自特性的约束,就像我原来的问题一样。

    【讨论】:

    • 请注意,如果您尝试使用 bindable,这样的方法会带来安全问题。
    猜你喜欢
    • 1970-01-01
    • 2020-11-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多