3

I have a simple Grails application. I have domains as below

class Author implements Serializable {
   ....
   static hasMany = [
        book : Book 
   ]
}

class Book implements Serializable{

   Author author
   Genres genres
   static belongsTo = [author: Author , genre: Genres ]
   static mapping = {
    .....
       author lazy: false
   }
}

class Genres implements Serializable{

    String title

}

Now I have a requirement where I have a list of Genres title, I need to retrieve all the authors who has atleast one book in one of those Genres. I need to write a named query in Author class. I tried the following query

hasGenre {cl ->
    'book.genre.title' in cl
}

And I pass a list of string as follows

 Author.hasGenre(genereTitleStringArray)

But this does not seems to be working. I have some other straightforward named-queries which works fine. So when I retrieve including "hasGenere" this does not seem to affect the retrieval. What am i doing wrong? I'm quite new to this area

Thanks in advance

Visahan
  • 1,130
  • 2
  • 14
  • 35

2 Answers2

1

Have you been using list() method? if no, you must use it to get your entity from namedQuery, because namedQuery return NamedCriteriaProxy.Class:

author = Author.hasGenre(genereTitleStringArray).list()

For me such code is working good, in my Author i have:

static namedQueries = {
    hasGenre { cl->
        'book.genres.title' in cl
    }
}

Book the same. What about Genres you must also add dependency one-one(if you haven't):

 static belongsTo = [book: Book]

or one to many:

static hasMany= [book: Book]

For me current code is working good, good luck.

P.S. I'm using grails 2.3.11

  • Book is associated with Generes by a Lazy Single-Ended Association. This is because I don't want books to be retrieved when a Genere object is retrieved. I'm using Grails 2.2.4. If i use the query `Author.hasGenre(genereTitleStringArray).list()` , then all the records are retrieved. the hasGenre method doesn't seem to affect the retrieval – Visahan Oct 15 '15 at 10:34
  • I just realized I defined labels as `Set book` in Author, Changed it to `Set book` and it's working. Thanks for the help – Visahan Oct 15 '15 at 12:10
0

The proper syntax would be

 static namedQueries = {
       hasGenre {genreName -> 
                book{
                   genres {  
                       eq 'title' genreName 
               } 
           }
       }
   }
Neoryder
  • 897
  • 2
  • 13
  • 26