FootballResultDbService.java

package com.mojosoft.demo.service;

import com.mojosoft.demo.cache.MatchKey;
import com.mojosoft.demo.entity.FootballResult;
import jakarta.persistence.EntityManager;
import jakarta.persistence.criteria.CriteriaBuilder;
import jakarta.persistence.criteria.CriteriaDelete;
import jakarta.persistence.criteria.Predicate;
import jakarta.persistence.criteria.Root;
import jakarta.transaction.Transactional;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * This class is responsible for deleting football results.
 */
@Service
public class FootballResultDbService {

  private final EntityManager entityManager;

  @Autowired
  public FootballResultDbService(EntityManager entityManager) {
    this.entityManager = entityManager;
  }

  /**
   * This method deletes the football results.
   *
   * @param keys the keys
   */
  @Transactional
  public void deleteAllByMatchKeys(List<MatchKey> keys) {
    CriteriaBuilder cb = entityManager.getCriteriaBuilder();
    CriteriaDelete<FootballResult> delete = cb.createCriteriaDelete(FootballResult.class);
    Root<FootballResult> root = delete.from(FootballResult.class);

    Predicate[] predicates = new Predicate[keys.size()];
    int index = 0;

    for (MatchKey key : keys) {
      predicates[index++] = cb.and(
          cb.equal(root.get("season"), key.season()),
          cb.equal(root.get("homeTeam"), key.homeTeam()),
          cb.equal(root.get("awayTeam"), key.awayTeam())
      );
    }

    delete.where(cb.or(predicates));
    entityManager.createQuery(delete).executeUpdate();
  }
}