我正在研究Spring Data JPA.考虑下面的示例,我将默认使用所有crud和finder功能,如果我想自定义查找器,那么也可以在界面本身轻松完成.
@Transactional(readOnly = true)
public interface AccountRepository extends JpaRepository<Account, Long> {
@Query("<JPQ statement here>")
List<Account> findByCustomer(Customer customer);
}
Run Code Online (Sandbox Code Playgroud)
我想知道如何为上述AccountRepository添加一个完整的自定义方法及其实现?由于它的接口我无法在那里实现该方法.
我正在使用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不提供此方法.
我怎么解决这个问题?
最好的祝福