2016-12-19 27 views
0

我有像列的表: ID,外部ID,名字,姓氏,电子邮件Grails的findAllBy()不工作

我的域名:

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] 

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

谢谢!

+1

'诠释id'过程中出现问题,当你运行的Grails运行的应用程序,每个领域都会自动创建领域'id'&'version'在数据库中,所以你必须删除这行'int id' – akiong

回答

1

你知道有很多不妥所有这一切

//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() 
} 

一些替代方法,并可能对依赖于数据库那么激烈寻找一个迭代你正在尝试实现具体布尔VS当前的方法

我也叫externalIdd因为当谈到.where有时具有相同的变量名作为所谓从而导致问题的改变

E2A 根据你的评论,如果你只需要身份证,那么一个ID通常是长的,因此您可以使用的严格定义 - DEF是更通用的,并且会返回任何东西。我已经提炼了只包含id的财产,所以如果它发现记录它将返回id,然后?:0L,如果没有发现返回0 L只要返回一个零长您可以用?: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 
    } 
+0

感谢您的回复。我试图通过使用externalId值拉取员工来获取id列的值。 – gibsonsg

+0

我已经在上面的每个模块中留下了一些进一步的评论,他们都是像你的方法,但严格定义他们期望返回什么。编辑过的示例中提供的最后一个示例应该能够提供您所需的内容。 – Vahid

0

您应该在类上调用findAllBy_(),而不是实例。此外,由于您只返回一个Employee而不是列表,因此应使用findBy_()。鉴于此,您的服务方法应如下所示:

def getEmployee(String externalId){ 
    return Employee.findByExternalId(exteranlId) 
} 
0

您不能拥有以Id结尾的属性。

myInstance.propertyId means get the property "Property" and its Id. 

而且我想有动态发现者产生因素这 -