Raymond Holguin
Raymond Holguin

Reputation: 1122

Use dynamic finders with list of Object IDs

With the given class structure

class MyObject {
   Status status;
}

class Status {
   Integer id;
}

I want to use dynamic finders to query based on a list of Status ID values. What I want to be able to do is something like this

MyObject.findAllByStatusInList([1,2,3]);

This does not work though because my list needs to be Status objects. I know I can build a criteria to do this, but I just want to know if there is a way to accomplish this with Dynamic Finders?

Upvotes: 1

Views: 456

Answers (3)

Surajit Mandal
Surajit Mandal

Reputation: 1

You can use this.

List<Integer > statuses = [1, 2, 3] MyObject.findAllByStatusInList(statuses)

Upvotes: 0

Anton Hlinisty
Anton Hlinisty

Reputation: 1467

You can use the where clause:

MyObject.where {status.id in [1,2,3]}.find()

UPD

Dynamic finders don't support aliasing so Criteria (or DetachedCriteria) is the solution to be used.

In case if Status class is a domain entity you could retrieve a list of them (or load their proxies) from the database and then query MyObjects by the status list.

So I see no other appropriate solution but using Criteria in your case.

Upvotes: 0

doelleri
doelleri

Reputation: 19702

You can still accomplish this using the dynamic finder.

def statuses = [1, 2, 3].collect { Status.load(it) }
MyObject.findAllByStatusInList(statuses)

load() will create a proxy for you that won't require retrieving the instance from the database as long as you don't access any properties other than id.

Upvotes: 1

Related Questions