【问题标题】:Set a Grails Domain Class as "No-Insert Mode"将 Grails 域类设置为“无插入模式”
【发布时间】:2025-12-06 01:10:02
【问题描述】:

我需要在我的 Grails 应用程序上使用一个复杂的查询。我没有使用复杂的criteriaBuilder(),而是执行了以下操作:

  1. 在数据库上创建View,比如ParentChildView
  2. 将其映射到域类中。
  3. 使用此ParentChildView 域类执行.list() 操作。

我想知道是否可以将此域类配置为 "select-only mode""no-insert-allowed mode"?— 你知道,只是为了确保如果某些开发人员不小心尝试插入此域时会抛出 Exception

【问题讨论】:

    标签: grails grails-orm


    【解决方案1】:

    根据我对您问题的理解,您不希望发生插入或确保更新。

    您的操作可能是其中之一。

    • 用户元编程和使保存方法抛出域异常。例如

      User.metaClass.static.save = {
           throw new IllegalStateException("Object is not in a state to be save.")
        }
      
    • 如果不确定元编程,您可以使用钩子,如下所示。

      def beforeInsert() {
          throw new IllegalStateException("Object is not in a state to be save.")
      }
      
      def beforeUpdate() {
          throw new IllegalStateException("Object is not in a state to be updated.")
      }
      
      def beforeDelete() {
          throw new IllegalStateException("Object is not in a state to be deleted.")
      }
      
    • 没有尝试mapWith 进行插入/更新,因为它实际上不允许创建表,但像域这样的一切都可用。

       static mapWith = "none"
      
    • 最后但同样重要的是,我们也可以使用事务,但这些不会有太大帮助。就像在服务中一样,您可以使用@Transactional(readOnly=true)。但这只会对服务有所帮助。

    • 此外,您可以禁用版本控制并希望缓存仅用于读取。

      static mapping = { 
        cache usage: 'read-only' 
        version false 
      } 
      

    我发现this topic about read-only domain 非常有用且值得。

    我不确定第三个子弹,但你也可以试试这个。

    希望对您有所帮助!

    【讨论】:

      最近更新 更多