简体   繁体   中英

Grails : Find domain class by property

I am pretty new to Grails/groovy and looking for a optimized way to write a code.

Domain class:

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

Now in a controller:

class VisitorsController {

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

At the commented line above, i want to get all Visitors objects that doesn't have status = OK and then go through a loop and update there status = REDO .

The statuses are defined in another class:

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

Any suggestions?

With minor modifications to enum and using where query instead of findAllBy would yield expected result.

//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'
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM