Home » Uncategorized » Groovy for Products Query

Groovy for Products Query

Here is a simple groovy code for setting its Boolean Attribute for all products.
Even you can use customized attribute.

import de.hybris.platform.category.model.CategoryModel
import de.hybris.platform.core.Registry
import de.hybris.platform.core.model.product.ProductModel;
import de.hybris.platform.servicelayer.model.ModelService
import de.hybris.platform.servicelayer.search.FlexibleSearchQuery
import de.hybris.platform.servicelayer.search.FlexibleSearchService
import de.hybris.platform.catalog.impl.DefaultCatalogVersionService;
import de.hybris.platform.catalog.model.CatalogVersionModel
import groovy.transform.Field
import org.apache.commons.collections.CollectionUtils;

@Field
FlexibleSearchService flexibleSearchService = Registry.getApplicationContext().getBean("flexibleSearchService");
@Field
ModelService modelService = Registry.getApplicationContext().getBean("modelService");
@Field
DefaultCatalogVersionService catalogVersionService = Registry.getApplicationContext().getBean("defaultCatalogVersionService");


def queryStaged = new FlexibleSearchQuery("SELECT {PK} FROM {Product} WHERE {catalogVersion} in ( {{ select {pk} from {catalogversion} where {version} = 'Staged' and {catalog} in ( {{ select {pk} from {catalog} where {id} = 'YOUR_PRODUCT_CATALOG_ID' }} ) }} )");


List<Object> resultStaged = flexibleSearchService.search(queryStaged).result

updateProducts(resultStaged);


def updateProducts( List<Object> products) {
    println(products.size())
    products.each {
        ProductModel product = it as ProductModel;

        println("Product: " + product.getCode());
        product.setWarrantable(Boolean.TRUE); // USE YOUR OWN ATTRIBUTE HERE
        modelService.save(product);
    }
}