3

I'm trying a query in Grails 1.2.1, find all products by tenant type.

My solution works but is very inefficient, first I retrieve all products and then find all matching results for the given tenant.

I found a related bug in JIRA: Enum as collection

class Product {
    Set<TenantType> tenants
    static hasMany = [tenants: TenantType]
}

enum TenantType {
    BICYCLE,
    MOTORCYCLE
}

def tenant = TenantType.BICYCLE
Product.list().findAll { product -> tenant in product.tenants }

Is there a more efficient way of querying for this data?

Arturo Herrero
  • 12,772
  • 11
  • 42
  • 73
  • Possible duplicate of [Grails select domain objects based on an enum value in an enum list property](http://stackoverflow.com/questions/4829823/grails-select-domain-objects-based-on-an-enum-value-in-an-enum-list-property) – Vinay Prajapati Oct 06 '15 at 10:25

3 Answers3

3

A similar question was asked here and as pointed out in the answer, it looks like Hibernate doesn't support criteria queries over collections of value types like enums. One option is to use an hql query instead:

Product.executeQuery('from Product p inner join p.tenants tenants
                      where tenants = :tenant', [tenant: TenantType.BICYCLE])
Community
  • 1
  • 1
Geli
  • 56
  • 2
1

Can be executed without join:

Product.executeQuery('from Product where :tenant in elements(tenants)', [tenant: TenantType.BICYCLE])
Koloritnij
  • 1,167
  • 1
  • 8
  • 15
0

Use named query in Product class something like

findByTenantType { tenantType->
        tenants{ eq 'value', tenantType}

    }

And then access this named query like this -

def product = Product .findByTenantType(TenantType.BICYCLE).get()

see similar blog - http://www.grailsbrains.com/search-parent-through-child-in-aggregation-relationship/

Alok Sinha
  • 171
  • 1
  • 3