Grails: a problem with nested associations in the criteria builder

I have a nasty problem with the criteria builder. I have an application in which one user has one calendar, and the calendar has many entries. It seems simple enough, but when I try to get calendar entries for a given user, I cannot access the user property (MissingMethodException). Here is the code:

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

I even tried the following variation:

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

This did not throw an exception, but also did not work.

Here are 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 ran into a similar issue noted in early 2008: http://jira.codehaus.org/browse/GRAILS-1412

But according to this link, this issue should have been resolved a long time ago.

What am I doing wrong?

+4
source share
5 answers

I finally found a mistake! The error was not related to the construction of the criteria. The problem in this case was that I had a user variable in scope, so when I tried to enter a user relation using

 calendar { user { eq("id", user.id) } } 

Grails thought I would like to call a custom object / variable with closure. I can again use the criteria of builders freely :-)

Thanks for your help and suggestions guys!

+9
source

If you have volume errors such as a question poster, you can always do the following. Lets say you have a user variable in your scope and then use

 def user = User.get(...) ... calendar { 'user' { eq("id", user.id) } } 

instead

 def user = User.get(...) ... calendar { user { eq("id", user.id) } } 
+3
source

I am not sure why your criteria do not work. I have always had problems so that they work perfectly correctly and find them stranger than HQL.

You can simply use HQL for your query, which I find more natural for writing and easier for parsing, since I'm used to looking in SQL.

Here is your query in HQL:

 Entry.executeQuery("from Entry e where e.calendar.user.id = :userId", [userId: theUser.id]) 
+1
source

Here is the thing

 def getEntries(User user) { def entries = Entries.createCriteria().list() { calendar { user { eq("id", user.id) } } } } 
0
source
 def entries = Entries.createCriteria().list() { 

Why did you write Records ? Your class name is Entry . Therefore, I would say that your line should read:

 def entries = Entry.createCriteria().list() { 
0
source

Source: https://habr.com/ru/post/1304243/


All Articles