在grails model association中需要帮助

时间:2013-10-11 10:58:53

标签: grails associations

我正面临着Grails模型关联的问题。这是问题:

  • 订阅者和客户从PartyRole扩展。
  • 客户可能拥有许多订户,订户属于客户。
  • 一方可能有很多PartyRole。
  • 个人和组织从派对延伸。
  • 一个人属于组织。
  • 一个人有很多个人资料,个人资料属于人。

现在我想编辑当前登录的用户(订阅者),其基本上是组织类型,具有组织属性,如orgName和orgSize。

我可以使用登录用户(订阅者)找到Person(firstName和lastName)和Profile(电子邮件)详细信息,但无法获取组织详细信息。代码如下。

 def profile = {
    Subscriber loggedinSubscriber = Subscriber.get( springSecurityService.principal.id )
    if (loggedinSubscriber == null){
      redirect(controller: "login" , action:"login");
    }
    else{
      println loggedinSubscriber
      Party person = Person?.get(loggedinSubscriber.party.id)
      Party org = Organization?.get(loggedinSubscriber.party.id)
      Profile profile = person?.profile
      [userInstance: person, authorityList: sortedRoles()]
    }
  }

当我尝试使用

获取组织详细信息时
Party org = Organization?.get(loggedinSubscriber.party.id)

我获得了null值,但同样地,我可以使用登录用户(订阅者)获取Person详细信息,并且两者都从Party扩展。

了解如何获取组织详细信息。

人:

package com.vproc.member

import com.vproc.enquiry.Enquiry;
import com.vproc.enquiry.Membership;
import com.vproc.enquiry.Notification;
import com.vproc.enquiry.Team;

class Person extends Party{

    String firstName
    String lastName

    Profile profile
    static belongsTo = [Organization]

    static constraints = {
        lastName nullable:true
        firstName blank:false

    }

}

**Organization:**

package com.vproc.member

import java.util.Date;

class Organization extends Party{

    String orgName 
    Person contact
    int orgSize
    boolean isVendor 

    static constraints = {
    }
}

配置文件:

package com.vproc.member

import java.util.Date;

import com.vproc.enquiry.Enquiry;
import com.vproc.enquiry.Membership;
import com.vproc.enquiry.Team;

class Profile {

    String emailAddress  //  field governed by privacy policy
    String phoneNumber   //  field governed by privacy policy
    Date dateCreated
    Date lastUpdated
    boolean isDefaultProfile
  String status
    static belongsTo = [person:Person]
    //ProfilePrivacyLevelEnum privacyLevel = ProfilePrivacyLevelEnum.Private

    static constraints = {
    }
}

订户:

package com.vproc.member

import java.util.Date;

import com.vproc.common.StatusEnum;
import com.vproc.enquiry.Discussion;
import com.vproc.enquiry.Enquiry;
import com.vproc.enquiry.Membership;
import com.vproc.enquiry.Notification;
import com.vproc.enquiry.SharedEnquiry;
import com.vproc.enquiry.Team;
import com.vproc.order.Seat;

class Subscriber extends PartyRole{

    transient springSecurityService

    String username
    String password
    boolean enabled
    boolean accountExpired
    boolean accountLocked
    boolean passwordExpired
    StatusEnum status
    Date dateCreated
    Date lastUpdated
    List<Contact> contacts ;

    static belongsTo = [ customer: Customer]
    static hasMany = [seats: Seat, ownedEnquiries: Enquiry,enquiresSharedWith: SharedEnquiry, enquiriesSharedBy: SharedEnquiry ,
         managedTeams: Team , memberships: Membership, contacts: Contact , sharedByContacts: SharedContact, sharedWithContacts: SharedContact,
          vContacts: VContact, partOf: VContact,  sharedbyVContacts: SharedVcontact, sharedWithVcontacts: SharedVcontact,
          notifications: Notification, discussions: Discussion]
    static mappedBy = [ managedTeams : "manager" , enquiresSharedWith: "sharedWith" , enquiriesSharedBy: "sharedBy"  ,
                                                   sharedByContacts : "sharedBy" , sharedWithContacts : "sharedWith" ,
                                                   vContacts: "forSubscriber"  ,  partOf :"ofContact",
                                                   sharedbyVContacts: "sharedby" , sharedWithVcontacts :"sharedWith"
                                                    ]


    static constraints = {
        username  validator : { val , obj ->
                                 if (obj.status != StatusEnum.Pending)
                                        val!= null
                              }
        username unique: true
        password validator : { val , obj ->
                                    if (obj.status != StatusEnum.Pending)
                                        val != null
                             }

        contacts nullable: true
        notifications nullable : true
        username nullable: true
        password nullable: true

    }

    static mapping = {
        password column: '`password`'
    }

    Set<Role> getAuthorities() {
        SubscriberRole.findAllBySubscriber(this).collect { it.role } as Set
    }

    def beforeInsert() {
        encodePassword()
    }

    def beforeUpdate() {
        if (isDirty('password')) {
            encodePassword()
        }
    }

    protected void encodePassword() {
        password = springSecurityService.encodePassword(password)
    }
}

方:

包com.vproc.member

import java.util.Date;

class Party {

    Date dateCreated
    Date lastUpdated

    static constraints = {
    }

    static mapping = {
        tablePerHierarchy false 
    }
}

成员角色:

包com.vproc.member

import java.util.Date;

class PartyRole {

    Party party

    Date dateCreated
    Date lastUpdated
    static constraints = {
    }
    static mapping = {
        tablePerHierarchy false 
    }
}

自举:

class BootStrap {

def init = {servletContext - &gt;

def userRole = Role.findByAuthority('ROLE_USER') ?: new Role(authority: 'ROLE_USER').save(failOnError: true)
def adminRole = Role.findByAuthority('ROLE_COMPANY_ADMIN') ?: new Role(authority: 'ROLE_COMPANY_ADMIN').save(failOnError: true)
def guestRole = Role.findByAuthority('ROLE_GUEST') ?: new Role(authority: 'ROLE_GUEST').save(failOnError: true)
def csrRole = Role.findByAuthority('ROLE_CSR') ?: new Role(authority: 'ROLE_CSR').save(failOnError: true)

//PersonRole.create adminUser, adminRole
def address = new Address( city : 'Pune' , stateCode : 'MH' , countryCode : 'IN'   )

def adminProfile = Profile.findByEmailAddress('sachin.jha@gmail.com' )?: new Profile(
    privacyLevel: ProfilePrivacyLevelEnum.Private,
    emailAddress:  "sachin.jha@gmail.com" ,
    phoneNumber: "9325507992",
    status : 'Active'
    ).save( failOnError: true)

 def adminPerson = Person.findByProfile( adminProfile) ?: new Person( firstName: 'admin' , lastName : 'user' , profile: adminProfile).save( failOnError: true) ;
 def vprocOrganization = Organization.findByOrgName('VPROCURE') ?: new Organization ( orgName: 'VPROCURE' , orgSize : 100 , mailingAddress: address, contact: adminPerson ).save( failOnError: true)
 def vprocCustomer = Customer.findByParty( vprocOrganization) ?: new Customer ( party: vprocOrganization, status: StatusEnum.Active  ).save(failOnError: true) ;
 def adminUser = Subscriber.findByUsername('admin') ?: new Subscriber( username : 'admin' ,  password : 'passw0rd' , enabled: true , party: adminPerson, customer: vprocCustomer , status: StatusEnum.Active ).save( failOnError: true)

 if ( !adminUser.authorities.contains(adminRole)){
      SubscriberRole.create adminUser, adminRole
    }

  JSON.registerObjectMarshaller(Date) {
     return it?.format("MM/dd/yyyy")
  }

    def userProfile = Profile.findByEmailAddress( 'sachin.jha.user@gmail.com') ?: new Profile(
        privacyLevel: ProfilePrivacyLevelEnum.Private,
        emailAddress: "sachin.jha.user@gmail.com",
        phoneNumber : "9325507992",
        status : 'Active'
        ).save( failOnError: true)

    def userPerson = Person.findByProfile( userProfile) ?: new Person( firstName: 'plain' , lastName : 'user' , profile: userProfile).save( failOnError: true) ;
    def plainUser = Subscriber.findByUsername('plainuser') ?: new Subscriber( username: 'plainuser', password : 'passw0rd' , enabled: true , party: userPerson, customer: vprocCustomer , status: StatusEnum.Active ).save( failOnError : true )
    if ( !plainUser.authorities.contains(userRole)){
        SubscriberRole.create  plainUser, userRole
    }

/*vprocCustomer.addToSubscribers(amdinUser)
vprocCustomer.addToSubscribers(plainUser)
vprocCustomer.save( failOnError : true);*/

}

def destroy = {
}

}

1 个答案:

答案 0 :(得分:1)

只需更改Person域类

即可
static belongsTo = [Organization]

static belongsTo = [organization:Organization]

并使用person.organization

访问人员实例中的组织信息