【问题标题】:How to get all the persistent properties of a grails Domain Class along with their constraints in a single Collection?如何在单个集合中获取 grails 域类的所有持久属性及其约束?
【发布时间】:2017-03-25 07:06:06
【问题描述】:

我需要在单个集合中获取有关特定 Grails 域类的所有信息,即持久属性和与它们相关的约束。我怎么做?

【问题讨论】:

    标签: java grails grails-orm


    【解决方案1】:

    从 grails 3.3 开始,接受的答案不再正确。 DefaultGrailsDomainClass 现在已弃用,单参数构造函数将抛出 mappingContext 尚未初始化的异常。

    注入grailsDomainClassMappingContext bean 并使用

    获取PersistentEntity
    def persistentEntity = grailsDomainClassMappingContext.getPersistentEntity(MyDomain.class.name)
    def propertyList = persistentEntity.getPersistentProperties()
    

    【讨论】:

    • GrailsDomainClassMappingContext 类现在似乎已经过时了。 HibernateMappingContext 类在我的设置中工作。
    • 确实,看起来这在 GORM 6.1(或更早版本)中已被弃用...可能比注入特定上下文更清洁的方法是从 grailsApplication.mappingContext 获取它...抽象它一个级别进一步
    【解决方案2】:

    以下内容为您提供了一个地图,其中属性名称作为键,约束地图作为值,适用于 Grails 3:

    def d = new DefaultGrailsDomainClass(MyDomain.class)
    
    def pp = d.persistentProperties.collectEntries {
        [it.name, d.constrainedProperties[it.name]?.appliedConstraints ]
    }
    

    【讨论】:

    • 这对我有帮助,但有没有办法找出当前属性是否允许为空?我在域中给出了约束。我试过但没有得到适当的约束值及其值。我想得到约束和它的价值
    【解决方案3】:

    我在 Grails 3.3.9 上使用这个解决方案:

    1) 自动装配此属性

    MappingContext grailsDomainClassMappingContext
    

    2) 检索propertyListconstrainedProperties

    ConstrainedDiscovery constrainedDiscovery = GrailsFactoriesLoader.loadFactory(ConstrainedDiscovery.class);
    PersistentEntity crlPe = grailsDomainClassMappingContext.getPersistentEntity(MyDomain.name)
    
    def propertyList = persistentEntity.getPersistentProperties()
    Map constrainedProperties = constrainedDiscovery.findConstrainedProperties(crlPe);
    

    此外,documentation 声明您应该能够通过调用此函数来检索约束:

    MyDomain.constrainedProperties
    

    它确实有效,但在日志中有一个烦人的警告。此解决方案可以很容易地与通过以下方式抑制的日志消息一起使用:

    logger("org.grails.core.DefaultGrailsDomainClass", ERROR)
    

    【讨论】:

      【解决方案4】:

      Grails 4.x

      def persistentEntity = grailsApplication.mappingContext.getPersistentEntity(object.getClass().getName())
      

      【讨论】:

        【解决方案5】:

        对于 Grails 4

        List<PersistentProperty> props = Holders
                        .grailsApplication
                        .mappingContext
                        .getPersistentEntity(object.class.name)
                        .persistentProperties
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2011-04-25
          • 1970-01-01
          • 2022-06-15
          • 1970-01-01
          • 2011-01-20
          • 2014-12-09
          相关资源
          最近更新 更多