你知道所有这些都有很多问题
//Create an instance of Employee which currently holds nothing
def employee = new Employee();
//With this empty object of Employ now do findAllByExternalId
employee.findAllByExternalId("1234");
你应该抬头看
//This will provide you with the entire employee
// domain class any it finds with that externalId.
// since it is declared as findAll
// the return will naturally be a list even though there may only be 1
def employees = Employee?.findAllByExternalId("1234")
但这一切都非常冗长,您要验证它是否存在或返回具有该 id 的所有员工的列表?您将其称为 getEmployee 所以我认为您正在尝试找到一个,但您正在通过 findAll 寻找迭代
// If you wanted just to check it exists return a boolean like this
//This will return result as a boolean
boolean getEmployee(externalIdd) {
return Employee.where { externalId == externalIdd }.exists()
}
//if you wanted purely employee entire object bound to first records
Employee getEmployee(externalIdd) {
return Employee.where { externalId == externalIdd }?.find()
}
//if you wanted a list of entire employees like the findAll above
List<Employee> getEmployee(externalIdd) {
return Employee.where { externalId == externalIdd }?.findAll()
}
是一些替代方法,并且可能在 db 上的强度较低,具体取决于您尝试实现的具体目标是布尔值与当前方法
我也打电话externalIdd
,因为.where
有时它的变量名与所谓的变量名相同会导致问题,因此改变
E2A
根据您的评论,如果您只需要 id 那么 id 通常是 Long 因此Long
您可以使用的严格定义def
- def 更通用并且会返回任何内容。我已经改进了仅包含属性的位置,id
因此如果找到记录,它将返回 id,?:0L
如果没有找到,则返回 0 L
For long 所以返回零 Long 您可以将其替换为?:null
或根本不声明它。
//if you only want to get the id as per comment
Long getEmployeeId(String externalIdd) {
return (Employee.where{externalId == externalIdd}.property('id')?\
.find()?:0L)
// Another way close to your findBy but manually declared
// and only returning id field.
// return Employee.find{externalId==externalIdd}?.id
}