将两个类的值保存在grails中



我有两个名为User.groovy和Employee.groovy的类,我使用MYSQL来保存数据。我想要的是创建一个新的User帐户并将其保存到User表中,同时将一些数据保存到Employee表中。我该怎么做?我已经尝试将用户扩展到Employee,但数据只保存到user,而没有保存到Employer。但是,如果我不扩展User,数据只保存到Employee。我应该怎么做才能使数据同时保存到两个数据库表中?请帮帮我。

实际上在我的课堂上有这个用户:

class User {
transient springSecurityService
String username
String password
boolean enabled
boolean accountExpired
boolean accountLocked
boolean passwordExpired
.....}

和员工:

class Employee {
String name
String email
String jobDesc
....}

那么我下一步该怎么办呢?很抱歉,我还在学习圣杯。

Grails范式(就脚手架而言)是一个形式统一的对象。只要你坚持这种模式,你就可以免费获得所有的好处,比如输入验证和错误报告(你也可以考虑在这里使用Fields插件http://grails.org/plugin/fields)。

然而,有时您需要通过单个表单收集信息并创建两个或多个对象。通常,当您需要启动新订阅并收集订阅详细信息(例如,订阅实体)和用户信息(用户实体)时,就会发生这种情况。这是指挥对象前来救援的地方。

http://grails.org/doc/latest/guide/theWebLayer.html#commandObjects

因此,您不需要扩展/弯曲SubscriptionController或UserController(或者UserController和EmployeeController,根据您的示例),而是创建SignUpController,它处理SignUpCommand对象。SignUpCommand对象不是用来保存的,它被用作SignUpController.create窗体的支持对象。当它验证时,您可以使用SignUpCommand对象数据初始化2个域对象(即Subscription和User),并将这些对象分别保存在同一事务中。

您可以将保存操作委托给服务,例如

if (signUpCmd.validate()) {
    SignUpService.save(signUpCmd))
}

或者在控制器内当场创建并保存两个对象

if (signUpCmd.validate()) {
    Subscription subscription = new Subscription(plan: signUpCmd.plan, ...)
    subscription.save()
    User user = new User(username: signUpCmd.username, ...)
    user.save()
}

这主要是品味和风格的问题。

与其直接对用户实例调用save(),不如调用一个在一个原子操作中同时保存用户和员工的服务类。比如:

class UserController {
/*Injection of your service in the controller class*/
def userService

然后在保存操作中,在同一控制器中:

userService.save(user) // userService.save(params)

在这个服务方法中,你将提取你想保存在不同表中的数据(用户或参数,无论你的船漂浮在什么地方),就像通常的用户对象一样。

最新更新