如何提取"查找或创建"方法来抽象类?(Spring Data Jpa)

use*_*654 5 java spring jpa spring-data

我正在使用Spring Data JPA,我有一堆像这样的存储库:

public interface CustomerRepository extends JpaRepository<Customer, Long> {}
Run Code Online (Sandbox Code Playgroud)

在存储库下我有服务,其中很多需要实现方法findOrCreate(String name),如下所示:

@Override
    @Transactional
    public List<Customer> findOrCreate(final String name) {
        checkNotNull(name);
        List<Customer> result = this.customerRepository.findByName(name);
        if (result.isEmpty()) {
            LOGGER.info("Cannot find customer. Creating a new customer. [name={}]", name);
            Customer customer = new Customer(name);
            return Arrays.asList(this.customerRepository.save(customer));
        }
        return result;
    }
Run Code Online (Sandbox Code Playgroud)

我想将方法​​提取到抽象类或某个地方,以避免为每个服务,测试等实现它.

抽象类可以是这样的:

public abstract class AbstractManagementService<T, R extends JpaRepository<T, Serializable>> {

    protected List<T> findOrCreate(T entity, R repository) {
        checkNotNull(entity);
        checkNotNull(repository);

        return null;
    }

}
Run Code Online (Sandbox Code Playgroud)

问题在于,由于我需要在创建新对象之前按名称查找对象作为字符串.当然接口JpaRepository不提供此方法.

我怎么解决这个问题?

最好的祝福

man*_*ish 1

创建包含此行为的自定义 JpaRepository 实现。请参阅这篇文章,了解编写自定义 JpaRepository 实现的示例。