grails - 如何获得持久化类中的对象列表的权限?

标签 grails groovy gorm

我有以下内容:

GroupMember.groovy

public class GroupMember{
  String userName
  String role
}

GroupProfile.groovy
public class GroupProfile{
  List<GroupMember> groupMembers = new ArrayList<GroupMember>()
}

GroupProfileController.groovy
public class GroupProfileController{
  def createProfile{
    GroupMember groupOwner = new GroupMember()
    groupOwner.userName = "testUser"
    groupOwner.role = "OWNER"
    groupOwner.save()

    GroupProfile groupProfile = new GroupProfile()
    def members = grouProfile.groupMembers
    members.add(groupOwner)
    groupProfile.save()

    GroupProfile.list() //This list contains my GroupMember instance with the correct info
    redirecT(action: myProfiles)
  }

  def myProfiles={
    GroupProfile.list() //This list contains my groupProfile that I made but no GroupMember info
  }
}

我的GroupProfile不会保存我的GroupMember信息。如何获取我的GroupProfile以保存GroupMember信息?

最佳答案

表示这种关系的正常方式是:

public class GroupProfile {
    static hasMany = [groupMembers: GroupMember]
}

这将自动在GroupProfile上生成一个称为addToGroupMembers的方法,该方法将创建关联。保存GroupProfile也将级联到组成员,因此添加成员后只需要调用一次save。

请注意,groupMembers集合实际上是Set的实例,不一定保留顺序。您可以将集合明确声明为List来保留顺序,但是它需要额外的开销,包括额外的数据库列,因此请确保这确实是您想要的。

查阅有关GORM的部分中的grails手册:http://grails.org/doc/latest/guide/GORM.html

关于grails - 如何获得持久化类中的对象列表的权限?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23392220/

相关文章:

grails - 针对值组合设置唯一约束

Groovy GPars,启动的每个线程都需要索引

java - groovy 属性类的 JAXB 注释

hibernate - 非空属性引用一个 transient 值-必须在当前操作之前保存 transient 实例

grails - Grails用户定义类型的域类属性的默认值

hibernate - Grails在内部将 “in”和 “isEmpty”组合在一起,或者忽略了 “isEmpty”

grails - 大气 meteor 和 meteor 一样吗

groovy - SOAP UI - 如何在文件中捕获 REST 原始响应

grails - GORM复合映射不起作用

xml - Grails:将XML节点添加为插件的doWithWebDescriptor中的最后一个web.xml节点