Grails domain Named query for a list of string - grails

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

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

The proper syntax would be
static namedQueries = {
hasGenre {genreName ->
book{
genres {
eq 'title' genreName
}
}
}
}

Related

how not to load hasMany entities from database using Grails

I've got 3 classes:
class Author {
static hasMany = [books: Book]
static belongsTo = [company: Company]
String name
}
class Book {
static mapping = {
collection "documents"
id generator: 'assigned',index: true, indexAttributes:[background:true, unique:true, dropDups:true]
}
String id
String name
}
class Company {
static mapping = {
collection "documents"
id generator: 'assigned',index: true, indexAttributes:[background:true, unique:true, dropDups:true]
}
String id
String name
}
I want to use
Author author = Author.getByCompanyAndBook(1,1);
but when running this Grails retrieves all the Book objects from the database.
I need those Books only as identifiers for the Author and I am not going to use those objects.
Is there a way for me to force Grails not to fetch the Books and Companies from the database?
I tried to use:
static mapping = {
books lazy: true
}
but still all of the Books and the Company were loaded.
Edit:
I am using mongo db as my database.
That's weird - collections are lazy by default, so getting an author shouldn't retrieve anything in the books collection until you access the books property. But regardless, even if it worked as expected I recommend that you avoid mapped collections. See this talk which shows why collections are unnecessarily expensive and provides workarounds to minimize the costs.

Creating Domain Relationships in Grails returns unable to resolve class error

Good day to all. I am very new in using grails and I have followed several tutorials for beginners using grails until I come up in creating domain relationships. However, I got stuck with this problem right now. I have 3 domain classes namely, todo, category and user. And as I defined their relationships, it returns me an error saying unable to resolve class. Please see my codes below. Please help. Thank you so much.
Todo.groovy Class
package todoScaff
class Todo {
String name
String note
Date createDate
Date dueDate
Date completedDate
String priority
String status
User owner
Category category
static belongsTo = [User, Category]
static constraints = {
name(blank:false)
createDate()
priority()
status()
note(maxsize:1000, nullable:true)
completedDate(nullable:true)
dueDate(nullable:true)
}
String toString() {
name
}
}
Category.groovy Class
package categoryScaff
class Category {
String name
String description
User user
static belongsTo = User
static hasMany = [todos: Todo]
static constraints = {
name(blank:false)
}
String toString(){
name
}
}
User.groovy Class
package userScaff
class User {
String userName
String fname
String lname
static hasMany = [todos: Todo, categories: Category]
static constraints = {
userName(blank:false, unique:true)
fname(blank:false)
lname(blank:false)
}
String toString(){
"$lname, $fname"
}
}
Since you've placed your domain classes in different packages, you must import the classes at the head of the file.
package categoryScaff
import todoScaff.Todo
import userScaff.User
class Category {
The same needs to happen in your other domain classes that reference classes outside the current package.

grails: multiple belongsTo with back reference

Is it possible to have a domain class that belongs to multiple domain classes with back reference? For instance:
class Person {
List<Book> books
static hasMany = [books: Book]
}
class Organization {
List<Books> books
static hasMany = [books: Book]
}
class Book {
def owner // what's the type?
static belongsTo = [Person, Books]
}
A Book can belong to a Person or an Organization, but not both.
Person and Organization have separate sequence IDs.
The solution I came up with is:
class Book {
Long ownerID
String ownerClass
static belongsTo = [Person, Books]
static transients = ['owner']
static constraints = {
ownerId(nullable:false, blank:false)
ownerClass(nullable:false, blank:false)
}
public BookOwner getOwner() {
grailsApplication.getArtefact("Domain", ownerClass)?.getClazz()?.get(ownerId)
}
}
where BookOwner is an Interface implemented by Person and Organization. So calling a bookInstance.owner will return a Person or Organization instance, both BookOwner.
My solution works well, but it doesn't feel right - a sure sign that I am not fully understanding what I'm doing. What's the best way to implement this? Should I completely give up on having the extremely convenient back reference?
Thank you
I guess, you should have made Owner superclass. Grails will create Owner table with field class meaning child class names (in your case: Person, Organization).

Grails Domain Class : hasOne, hasMany without belongsTo

I am new to Grails.
Can I use "hasOne" or "hasMany" without using "belongsTo" to another domain-class?
Thanks in advance.
Yes, you can. See examples in Grails doc: http://grails.org/doc/2.3.8/guide/GORM.html#manyToOneAndOneToOne
hasMany (without belongsTo) example from the doc:
A one-to-many relationship is when one class, example Author, has many
instances of another class, example Book. With Grails you define such
a relationship with the hasMany setting:
class Author {
static hasMany = [books: Book]
String name
}
class Book {
String title
}
In this case we have a unidirectional one-to-many. Grails will, by
default, map this kind of relationship with a join table.
hasOne (without belongsTo) example from the doc:
Example C
class Face {
static hasOne = [nose:Nose]
}
class Nose {
Face face
}
Note that using this property puts the foreign key on the inverse
table to the previous example, so in this case the foreign key column
is stored in the nose table inside a column called face_id. Also,
hasOne only works with bidirectional relationships.
Finally, it's a good idea to add a unique constraint on one side of
the one-to-one relationship:
class Face {
static hasOne = [nose:Nose]
static constraints = {
nose unique: true
}
}
class Nose {
Face face
}
Yes you can, but it behave differently
class Author {
static hasMany = [books: Book]
String name
}
class Book {
String title
}
In this case if you delete Author the books still existing and are independent.
class Author {
static hasMany = [books: Book]
String name
}
class Book {
String title
static belongsTo = [author: Author]
}
In this other case if you delete the Author it will delete all the books pf that author in cascade.
Many-to-one/one-to-one: saves and deletes cascade from the owner to the dependant (the class with the belongsTo).
One-to-many: saves always cascade from the one side to the many side, but if the many side has belongsTo, then deletes also cascade in that direction.
Many-to-many: only saves cascade from the "owner" to the "dependant", not deletes.
http://grails.org/doc/2.3.x/ref/Domain%20Classes/belongsTo.html
yes very easy like a class defintion but only specify hasMany but no need for hasOne
class Student {
String name
User userProfile
static hasMany =[files:File]
}
class User {
String uname
Student student
}
class File {
String path
Student student // specify the belongs to like this no belong to
}
Done!!

How to set unique hasMany relations based class properties?

I have two domain classes:
class Book {
String name
static hasMany = [articles: Article]
}
class Article {
String name
static belongsTo = [book: Book]
}
I want to validate that a book does have only unique articals in terms of the article name property. In other words: there must be no article with the same name in the same book.
How can I ensure that?
You can do this with a custom validator on your Book class (see documentation).
A possible implementation can look like this:
static constraints = {
articles validator: { articles, obj ->
Set names = new HashSet()
for (Article article in articles) {
if (!names.add(article.name)) {
return false
}
}
return true
}
}
In this example I am using a java.util.Set to check for duplicate names (Set.add() returns false if the same name is added twice).
You can trigger the validation of an object with myBookInstance.validate().

Resources