views:

750

answers:

4

I have a frustrating problem with the criteria builder. I have an application in which one user has one calendar, and a calendar has many entries. Seems straightforward enough, but when I try to get the calendar entries for a given user, I can't access the user property (MissingMethodException). Here's the code:

def getEntries(User user) {
  def entries = [ClassName].createCriteria().list() {
    calendar {
      user {
        eq("id", user.id)
      }
    }
  }
}

I have even tried the following variation:

def getEntries(User user) {
  def entries = [ClassName].createCriteria().list() {
    calendar {
      eq("user", user)
    }
  }
}

That did not raise an exception, but didn't work either.

Here's the relevant parts of the domain classes:

class Calendar {
    static belongsTo = [user: User]
    static hasMany = [entries: Entries]

    ...
}

class User {
    Calendar calendar

    ...
}

class Entry {
    static belongsTo = [calendar: Calendar]

    ...
}

When Googling I came across a similar problem noted in early 2008: http://jira.codehaus.org/browse/GRAILS-1412

But according to that link this issue should have been solved long ago.

What am I doing wrong?

+1  A: 

I'm not sure why your criteria isn't working. I've always had some problems getting them to work quite right and find them more fiddly than HQL.

You could just use HQL for your query, which I find more natural to write and easier to parse since I'm used to looking as SQL.

Here's your query in HQL:

Entry.executeQuery("from Entry e where e.calendar.user.id = :userId", [userId: theUser.id])
Ted Naleid
Thanks Ted, I'd much prefer to have criteria since I think they are more readable and easier to refactor. But I will use HQL in the meanwhile, but it disturbs me that criteria builder isn't working.
Mr.B
A: 

Here is a thing

def getEntries(User user) {
 def entries = Entries.createCriteria().list() {
          calendar { 
             user { 
              eq("id", user.id)
             }
          } 
      }  
}
Amit Jain
sorry I misspelled earlier, It should of course be eq("id", user.id)but that didn't work either, I still get the same error...
Mr.B
A: 
def entries = Entries.createCriteria().list() {

Why did you wrote Entries? Your Classname is Entry. So i would say your Line should read:

def entries = Entry.createCriteria().list() {
You're right, another misspell from my part. Howerver, this still doesn't fix my problem :-(
Mr.B