【问题标题】:Grails : Find domain class by propertyGrails:按属性查找域类
【发布时间】:2015-02-03 17:40:27
【问题描述】:

我对 Grails/groovy 很陌生,正在寻找一种优化的方式来编写代码。

领域类:

class Visitors {
    int ID;
    String destination;
    String status; // Status can be OK, FAIL, DONE, REDO, NEW, LAST, FIRST
    .........
    ..........
}

现在在控制器中:

class VisitorsController {

    def getVisitors() {
        Visitors.findAllByStatus().each { } // This is where i have confusion
  }
}

在上面的注释行中,我想获取所有具有status = OK的访客对象,然后通过一个循环并在那里更新状态 = 重做

状态在另一个类中定义:

public enum VisitorsStatusEnum { NEW, OK, FAIL, DONE, REDO, LAST, FIRST }

有什么建议吗?

【问题讨论】:

    标签: grails groovy


    【解决方案1】:

    对枚举稍作修改并使用where 查询而不是findAllBy 将产生预期的结果。

    //src/groovy
    enum VisitorsStatusEnum { 
        NEW('NEW'), OK('OK'), FAIL('FAIL'), 
        DONE('DONE'), REDO('REDO'), LAST('LAST'), FIRST('FIRST')
    
        private final String id
    
        private VisitorsStatusEnum(String _value) { 
            id = _value 
        }
    
        String getId() { id }
    }
    
    // Domain class
    class Visitors {
        Integer ID
        String destination
        VisitorsStatusEnum status
    }
    
    //Controller
    class VisitorsController {
        def getVisitors() {
            def query = Visitors.where { 
                status != VisitorsStatusEnum.OK 
            }
    
            // Prefer batch update instead
            query.updateAll( status: VisitorsStatusEnum.REDO )
    
            render 'Updated'
        }
    }
    

    【讨论】:

    • 我收到一个错误:无法查询属性“it” - 类上没有这样的属性
    • 更新了答案。在 where 查询中应该是 status != VisitorsStatusEnum.OK 而不是 it.status != VisitorsStatusEnum.OK
    • 还要注意上面的action方法中的实现是一个例子。实现可能会根据您的需要而有所不同(例如,渲染/重定向/等)。有关详细信息,请参阅文档。
    • 我已接受您的回答。有没有办法像我在原始问题中提到的那样使用 EACH?因为为了我的目的,我需要一个访客类的对象,它会循环。
    • 是的,你可以。 query.list() 会给出一个可迭代的访问者列表。您可以将动态查找器用作Visitor.findAllByStatusNotEqual(VisitorsStatusEnum.OK),而不是使用where 查询。但是 where 查询是 DetachedCriteria 并且是惰性操作。
    猜你喜欢
    • 1970-01-01
    • 2011-09-14
    • 1970-01-01
    • 2014-01-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-01-28
    • 1970-01-01
    相关资源
    最近更新 更多