Grails 域类构造函数使用 id 而不是对象

标签 grails grails-orm grails-domain-class

我的域类如下所示:

class UserEvent { 
    User user
    Event event
    boolean isAttending
}

生成的数据库表看起来具有以下列:

[ID , EVENT_ID, USER_ID , IS_ATTENDING ]

我有事件对象和用户对象的唯一ID(user_id)。 我想仅使用此数据创建新的 UserEvent 对象,而不加载 User 对象,它可能看起来像这样:

def userEvent = new UserEvent(user:['id':user_id],isAttending: true, event: event)

我尝试了很多方法,但没有找到解决方案。我认为这绝对是可能的,因为它是通过 Controller 中的参数以类似的方式完成的,其中仅包含关联对象的 id:

 def userEvent= new UserEvent(params)

我期待找到解决方案。谢谢。

最佳答案

当你说“不加载用户对象”时,你可以这样做:

def userEvent = new UserEvent(user:User.load(user_id), isAttending: true, event: event)

get 不同,load方法不访问数据库。相反,它创建一个代理对象,仅在第一次访问非 id 属性时从数据库获取数据。

关于Grails 域类构造函数使用 id 而不是对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11668339/

相关文章:

grails - 我该怎么办:在grails g:select中需要=“false”?

grails - 在 grails 域类中声明排序关联的最佳方法是什么?

grails - 保存相关实体

Grails + GORM : What is the default equals() implementation in GORM?

grails - 解释Grails中的belongsTo

grails - Grails中的下拉菜单

unit-testing - 覆盖 Grails GORM 域类上的事件关闭以进行单元测试

grails - 为什么 Grails 命令对象默认提交对域对象的更改?

grails - grails oracle连接超时

mongodb - Grails MongoDB 列表不更新,我做错了什么吗?