gpt4 book ai didi

grails - GORM 中的三个域类关系

转载 作者:行者123 更新时间:2023-12-02 13:59:44 24 4
gpt4 key购买 nike

gorm 有没有一种特殊的方法来映射这样的三个域类关系:

1 person belongs to N companies with M given roles (one or more roles for a given company)

提前致谢。

最佳答案

http://www.grails.org/Many-to-Many+Mapping+without+Hibernate+XML (我认为它是最新的)。

请注意:http://codedumpblog.blogspot.com/2010/02/grails-many-to-many-with-lists.html

下面的代码适用于我使用 grails 1.2.0。但似乎我不得不做很多 save() 的。不要忘记制作 Controller 并设置 scaffold=domain_class

package p

class Company {
String toString() { "$name"
}
static hasMany=[roles:Role]
static constraints = {
}
String name
}

package p

class Role {
String toString() { "$name"
}
static belongsTo=[company:Company]
static hasMany=[personRoleAssociations:PersonRoleAssociation]
static constraints = {
}
String name
}

package p

class Person {
String toString() { "$name"
}
static hasMany=[personRoleAssociations:PersonRoleAssociation]
static constraints = {
}
String name
}

package p

class PersonRoleAssociation {
String toString() { "${person.name} as ${role.name}"
}
static belongsTo=[person:Person,role:Role]
static constraints = {
}
}


import p.*
class BootStrap {

def init = { servletContext ->
Person dick=new Person(name:'dick')
Person jane=new Person(name:'jane')
dick.save()
jane.save()
Company ibm=new Company(name:'ibm')
ibm.save()
Role ibmManager=new Role(name:'ibmmanager')
Role ibmPeon=new Role(name:'ibmpeon')
ibm.addToRoles(ibmManager)
ibmManager.save()
ibm.addToRoles(ibmPeon)
ibmPeon.save()
ibm.save()
Company sun=new Company(name:'sun')
sun.save()
Role sunManager=new Role(name:'sunmanager')
Role sunPeon=new Role(name:'sunpeon')
sun.addToRoles(sunManager)
sunManager.save()
sun.addToRoles(sunPeon)
sunPeon.save()
sun.save()
PersonRoleAssociation dickManager=new PersonRoleAssociation()
dick.addToPersonRoleAssociations(dickManager)
ibmManager.addToPersonRoleAssociations(dickManager)
PersonRoleAssociation dickPeon=new PersonRoleAssociation()
dick.addToPersonRoleAssociations(dickPeon)
sunPeon.addToPersonRoleAssociations(dickPeon)
PersonRoleAssociation janeManager=new PersonRoleAssociation()
jane.addToPersonRoleAssociations(janeManager)
sunManager.addToPersonRoleAssociations(janeManager)
PersonRoleAssociation janePeon=new PersonRoleAssociation()
jane.addToPersonRoleAssociations(janePeon)
ibmPeon.addToPersonRoleAssociations(janePeon)
}
def destroy = {
}
}

关于grails - GORM 中的三个域类关系,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2269320/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com