Grails- how to get part of the values in set collection?

794 views Asked by At

I have a domain which call party and has many invitees. party.invitees give me a the set collection of the invitees. I want to get only some of the invitees so I try do do the followinf in my service.

partInvitees= event?.invitees?.findAll{[offset: 3,max: 8]}

It doesn't give the correct result. It gives me all the invitees instead only the specific I have asked.

2

There are 2 answers

0
lifeisfoo On

You could use the GORM list() method to get the entire collection for a domain class. If you want only a subset of the collection you could use list() with some parameters.

If your domain class is named Invite, you should use Invite.list(max: 8, offset: 3, sort: "id", order: "asc") to get the subset described in your question. Keep in mind that different sort/order params could give you different results.

See the list() or listOrderBy() documentation for more information.

If you want Invites only for a specific Event you should read the Deigote answer.

7
Deigote On

The findAll method you are invoking in there is not from GORM, but from Groovy Collections. So even if you paginate it (which is not possible directly in Groovy, AFAIK), you'll be bringing the whole collection into memory. If you don't mind, just do:

event?.invitees[offset..(offset-1)+max]

If the collection is too big and you don't want to bring it to memory, you can also query the Invitee directly:

Invitee.findAllByEvent(event, [offset: 3,max: 8])

But be aware that the order won't be necessarily the same, since Gorms' findAllBy doesn't know about the collection index (I'm assuming invitees is a list). You can make the collection index-aware, but it's a bit tricky.