【问题标题】:How to get the value of one element in a List in groovy/grails如何在groovy / grails中获取列表中一个元素的值
【发布时间】:2016-02-04 15:48:07
【问题描述】:

执行 createCriteria 查询后,我有一个对象列表,其中只有 1 个项目,其中包含 7 个字符串。我想做的只是得到这七个元素之一??

List<Object> result - com.test.MyService.getConfig(String, String, String, String, String, String, String)

这是我在列表中得到的元素:

[name:John, surname:John city:Rome, car:BMW, country:Italy, day:Monday, color:Red,]

例如,我希望访问以获取字符串“国家”以在方法中返回它:

我正在尝试这样做:

result.get(4)

我遇到了这个错误:

java.lang.IndexOutOfBoundsException: Index: 4, Size: 1

【问题讨论】:

    标签: list grails groovy criteria hibernate-criteria


    【解决方案1】:

    试试

    def oneObject = YourDomainClass.createCriteria().get{
         //add your criteria if any
    }
    return oneObject.country
    

    您会得到java.lang.IndexOutOfBoundsException: Index: 4, Size: 1,因为当您执行YourDomainClass.createCriteria().list{} 时,您会得到一个列表 YourDomainClass 对象(其中只有一个对象)。所以如果你想使用YourDomainClass.createCriteria().list{}你应该执行:

    def objects = YourDomainClass.createCriteria().list{}
    if(objects) //check if any object is in list
        return objects[0].country
    

    【讨论】:

    • 我无法访问.country
    • 请更具体一点:您在我的解决方案中遇到了什么样的错误?你两个都试过了吗?
    【解决方案2】:

    你可以做的是:

    1. 要么就做result.first().country
    2. 或者,如果您确定条件将始终返回单个结果,则使用 get 而不是 list
    3. 如果您只需要一个属性,则使用投影仅获取该属性而不是整个对象。

    def result = DomainClass.createCriteria().list { //or get resultTransformer(CriteriaSpecification.ALIAS_TO_ENTITY_MAP) projections { property("country", "country") } }

    在这种情况下,当使用.list{} 获取国家/地区的值时:

    1. 带有结果转换器return result.first().country
    2. 没有结果转换器:return result.first()

    当使用.get{}而不是.list{}时:

    1. 带有结果转换器return result.country
    2. 没有结果转换器:return result

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-06-17
      • 1970-01-01
      • 2012-08-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-12-31
      相关资源
      最近更新 更多