Search code examples
grailsgrails-orm

GORM findAll doesn't work


A have class Product:

class Product {
    static hasMany = [attributeValues: ProductAttributeValue]

    String productId
    String manufacturer
    BigDecimal price

    static constraints = {
        productId unique: true, blank: false
        manufacturer blank: false
        price min: BigDecimal.ZERO
    }
}

I want to find all products, which productId contains substring 'filter'. I wrote next code:

Product.findAll {it.productId.contains(filter)}

But it doesn't work. Why?


Solution

  • this should't work at all! you have 2 options here:

    1) you use propper GORM techniques like criteria query or HQL, the would look like:

    Product.findAllByProductIdIlike( "%${filter}%" ) // dyn-finders
    Product.withCriteria{ ilike 'productId', "%${filter}%" } // criteria    
    Product.findAll{ ilike 'productId', "%${filter}%" } // criteria
    Product.findAll( "from Product where productId like '%?%'", [ filter ] ) // hql`
    

    2) or use filtering on the whole dataset in grails app's memory (instead of the db) - NOT recommended:

    Product.list().findAll{ it.productId.contains(filter) }