Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to extract "find or create" method to abstract class? (Spring Data Jpa)

I'm using Spring Data JPA and I have a bunch of repositories like this one:

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

Under repositories I have services and a lot of them need to have implemented method findOrCreate(String name) like this one:

@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;
    }

I would like to extract method to the abstract class or somewhere to avoid implementing it for each services, testing and so on.

Abstract class can be look like this:

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

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

        return null;
    }

}

And the problem is it due to the fact that I need to find object by name as a string before creating a new one. Of course interface JpaRepository doesn't offer this method.

How can I solve this problem?

Best Regards

like image 651
tomasz-mer Avatar asked Nov 09 '22 17:11

tomasz-mer


1 Answers

Create a custom JpaRepository implementation that includes this behaviour. See this post for an example of writing a custom JpaRepository implementation.

like image 71
manish Avatar answered Nov 15 '22 07:11

manish