不要这样做——即使你可以让它在 Groovy 中更有用,这也是个坏主意。不过,在这种情况下,有一些简单的解决方案。如果您只是传递 Employee 实例并将其保存在 service 方法中,则无需返回任何内容:
void save(Employee employee) {
employee.save(flush:true)
}
这是因为如果成功,id 会在你传入的实例上设置,如果没有,errors 属性中会出现一个或多个验证错误(你不需要返回一般错误实际有用的错误消息可用时的消息)。
例如,这将是您在控制器中调用服务的代码:
def employee = new Employee(...)
fooService.save(employee)
if (employee.hasErrors()) {
// do something with employee.errors
}
else {
// success - use the id if you need via employee.id
}
如果你想传入数据来创建和保存新实例并返回一个Employee(这是我通常采取的方法),类似:
Employee save(String name, int foo, boolean bar, ...) {
Employee employee = new Employee(name: name, foo: foo, bar: bar, ...)
employee.save(flush:true)
return employee
}
在第二种情况下,将save 调用和return 分开很重要,因为如果出现验证错误,save 将返回null,并且您希望始终返回一个非空实例。所以不要这样做:
return employee.save(flush:true)
如果将它们分开,您可以检查错误和/或 id。
另外,请确保不要像在代码中那样在服务中使用闭包 (def save = { ...)。只有方法是事务性的,因为 Spring 事务处理不知道 Groovy 闭包——它们只是 Groovy 调用的字段,就好像它们是方法一样,但它们不是。