Search code examples
spring-bootspring-dataspring-repositories

Extend Spring Data Repository


I would like to introduce a <T> T findOrCreate(Supplier<Optional<T>> finder, Supplier<T> factory) to all of my repositories. So created a new Interface

@NoRepositoryBean
public interface ExtendedJpaRepository<T, ID extends Serializable> extends JpaRepository<T, ID> {
    T findOrCreate(Supplier<Optional<T>> finder, Supplier<T> factory);
}

.

public class ExtendedJpaRepositoryImpl<T, ID extends Serializable> extends SimpleJpaRepository<T, ID> implements ExtendedJpaRepository<T, ID> {

    private final JpaEntityInformation entityInformation;
    private final EntityManager entityManager;

    public ExtendedJpaRepositoryImpl(JpaEntityInformation entityInformation, EntityManager entityManager) {
        super(entityInformation, entityManager);
        this.entityInformation = entityInformation;
        this.entityManager = entityManager;
    }

    @Override
    public T findOrCreate(Supplier<Optional<T>> finder, Supplier<T> factory) {
        throw new NotImplementedException("No implemented yet");
    }
}

Then I use this interface in my concrete repositories, e.g. RecipeIngredientRepository:

public interface RecipeIngredientRepository extends ExtendedJpaRepository<RecipeIngredient, Long> {}

When I finally inject the repository to my service I get the following exception:

java.lang.IllegalStateException: Failed to load ApplicationContext
...
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'recipeIngredientRepository': Invocation of init method failed; nested exception is org.springframework.data.mapping.PropertyReferenceException: No property find found for type RecipeIngredient! Did you mean 'id'?

It is searching for a find property in my entitiy RecipeIngredient. I did not want it to do this. I think this is related to JPA Query Methods. So I changed the name from findOrCreate to xxx to Bypass any query method detection - without success. It searches for a xxx property then.

What does make spring data look for this property? I'm using org.springframework.boot:spring-boot-starter-data-jpa.


Solution

  • You need to specify your customized repository implementation via @EnableJpaRepositories(repositoryBaseClass = ExtendedJpaRepositoryImpl.class).

    Take a look at the reference docs: Adding custom behavior to all repositories.