Search code examples
hibernategrailsgrails-orm

How to write this Grails GORM Hibernate query


New to GORM, can't figure how to do this query. Here are my domain classes (minus unnecessary info):

User {...} //domain object (from springsecurity)

BasicProfile {
   User user
   static hasMany = [applicants:Applicant]
}

Applicant {
   static belongsTo = BasicProfile
   int applicantNumber
}

My BasicProfile will always have 1 or 2 Applicants. Right now I'm using a hasMany, though I may switch to having an applicant1 and applicant2 in the BasicProfile at a later time.

What I am trying to get in pseudo sql:

select the applicant object from a BasicProfile where the applicantNumber = 1 and BasicProfile.user.id == springSecurityService.principal.id

Basically I'm trying to get back one of the Applicant objects from the BasicProfile, given the session user and an applicantNumber.


Solution

  • How about this?

    User user = User.load(springSecurityService.principal.id)
    def applicant = BasicProfile.findByUser(user)
                                .applicants?.find{it.applicantNumber == 1}
    

    Inspired by Burt's answer and using dynamicFinders.