【问题标题】:How to extract "find or create" method to abstract class? (Spring Data Jpa)如何将“查找或创建”方法提取到抽象类? (Spring Data Jpa)
【发布时间】:2015-05-29 04:54:31
【问题描述】:

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

public interface CustomerRepository extends JpaRepository<Customer, Long> {}

在存储库下,我有服务,其中很多需要像这样实现方法 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;
    }

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

抽象类可以是这样的:

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

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

        return null;
    }

}

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

我该如何解决这个问题?

最好的问候

【问题讨论】:

  • 这里有一个竞争条件:当一个尚未创建的实体上的两个线程调用此方法时。两者都将尝试获取(并且找不到任何东西),然后save() 之一将失败。

标签: java spring jpa spring-data


【解决方案1】:

创建一个包含此行为的custom JpaRepository implementation。有关编写自定义 JpaRepository 实现的示例,请参阅 this post

【讨论】:

  • 我确实像你说的那样。根据帖子。效果很好。谢谢!
猜你喜欢
  • 2012-04-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-03-28
  • 2020-01-23
  • 2015-05-11
相关资源
最近更新 更多