gpt4 book ai didi

grails - Grails findAllBy()无法正常工作

转载 作者:行者123 更新时间:2023-12-02 15:19:14 24 4
gpt4 key购买 nike

我有一个带有列的表:
id,externalId,名字,姓氏,电子邮件

我的网域:

class Employee {

int id
String externalId

static mapping = {
table "Employee"

id column: "Id"
externalId column: "externalId"
version false
}
}

我的服务:
class EmployeeService {

def getEmployee(externalId) {
def employee = new Employee();

employee.findAllByExternalId("1234");

return employee
}

日志中的错误消息说:
No signature of method Employee.findAllByExternalId is applicable for argument types (java.lang.String_ values: [1234]

我的目标是加载一个instance,其中externalId与我给的匹配。我究竟做错了什么?

谢谢!

最佳答案

您确实知道所有这些都有很多错误

//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的要求不高,具体取决于您要尝试实现的是 bool(boolean) 值还是当前方法

我也称 externalIdd是因为当 .where有时与所调用的变量名相同时,会引起问题,因此更改

E2A
根据您的评论,如果您仅需要id,则id通常为Long,因此对 Long的严格定义可以使用 def-def更通用,并且将返回任何内容。我已经完善了仅包含 id属性的位置,因此,如果找到记录,它将返回id,然后返回 ?:0L,如果没有找到返回0 L很长一段时间,因此返回零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
}

关于grails - Grails findAllBy()无法正常工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41227279/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com