cancel
Showing results for 
Search instead for 
Did you mean: 

How to delete the records based on conditions after fetching the data from database using groovy script?

pankajjha
Explorer
0 Kudos

Hi All,

Please provide the solution ASAP.

Regards, Pankaj

Accepted Solutions (1)

Accepted Solutions (1)

former_member704915
Participant
0 Kudos

I assume you have fetch the list of records that needs to be deleted. Use the below sample groovy logic

 ResultSet resultset = <<your list of data from database>>
 List<CartModel> cartModelList;
 while (resultset.next()) {                           
  System.out.println(resultset.getString("pk"));
  if(<<your condition for deletion>>){
         final CartModel deleteCart = modelService.get(PK.parse(String.valueOf(resultset.getString("pk").trim()))); //example to delete cart
         cartModelList.add(deleteCart);
  
  }
  }
  modelService.removeAll(cartModelList);

I have shown an example to delete a list of carts. Replace it with your requirement and put necessary exception handling blocks.

rohit31_raj92
Active Participant
0 Kudos

Note: Commit mode needs to be turned on to reflect the changes in db else the changes will not persist inside db.

Thanks

Answers (1)

Answers (1)

andyfletcher
Active Contributor
0 Kudos

Just use the Groovy each method to to iterate over the collection returned from a flexible search.

You can filter either with the flexible search where clause or filter the collection itself using findAll

e.g. this will delete products that have a code starting with X and are approved

 flexibleSearchService.search(/select {pk} from {product} where {code} like 'X%'/).result
   .findAll { it.approvalStatus == de.hybris.platform.catalog.enums.ArticleApprovalStatus.APPROVED }
   .each { modelService.remove it }

it is the implicit parameter to the closure, in this case the current product in the collection.