Search code examples
grailshqlgrails-ormcriteria

Querying associations with enum collections in Grails


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?


Solution

  • 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])