Reputation: 78136
I have the next two domain classes in a grails application:
class Room {
String name
RoomType roomType
def static findAllByUser = { user, params ->
List<Room> rooms = Room.findAll("from Room r where r.roomType.user = :user", [user: user], params)
return rooms
}
}
class RoomType {
String name
User user
}
I wan to be able to retrieve all the rooms created by a particular user.
def currentUser = currentUser()
def rooms = Room.findAllByUser(currentUser)
In order to achieve that I implemented the clousure findAllByUser in the Room domain class.
However, when I invoke the closure i get a Null Pointer exception in this line.
List<Room> rooms = Room.findAll("from Room r where r.roomType.user = :user", [user: user], params)
The user is not null. So It must be my poor HQL. Can anyone help me?
Upvotes: 2
Views: 316
Reputation: 1882
I think a better bet would be to use a named query. It's nicer looking and can provide more functionality too:
Just add this to your Room domain class
static namedQueries = {
byUser { findUser ->
roomType {
eq 'user', findUser
}
}
}
And then call it like this:
def roomsByUser = Room.byUser(currentUser).list()
Upvotes: 4
Reputation: 1043
Works for me:
1) set default behaviour to 2nd parameter 'params' if u don't use it!
class Room {
String name
RoomType roomType
def static findAllByUser = { user, params = [sort:'name'] ->
List<Room> rooms = Room.findAll("from Room r where r.roomType.user = :user", [user: user], params)
return rooms
}
}
2) rename 'currentUser' variable to 'user' for example (i suppose that closure name is similar to variable name => not good)
def user = currentUser()
def rooms = Room.findAllByUser(user)
But more elegant solution is to put query logic into the grails service (e.g. RoomService.groovy)
Upvotes: 2