将 Grails 域 Class 设置为 "No-Insert Mode"

Set a Grails Domain Class as "No-Insert Mode"

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

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

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

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

你的行动可能是其中之一。

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

    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 进行插入/更新,因为它实际上不允许创建 table 但像域这样的一切都可用。

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

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

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

我发现 this topic about read-only domain 非常有帮助和价值。

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

希望对您有所帮助!