【发布时间】: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