How to create a findAllByUser query where the user is a member of an embedded class?

advertisements

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?


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()