Search code examples
spring-profilesspring-repositories

Spring Repositories with different profiles


I have two different profiles and want to have two different repositories for this profiles. But it's repositories for one entity and it's just have different conditions in query.

I try to do this:

It's my base interface for repository:

public interface RepositoryBaseInterface extends CrudRepository<MyEntity, Long> {
    List<MyEntity> getEntities();
}

And I have two profiles repository:

@Repository
@Profile("profile1)
public interface ProfileRepository extends RepositoryBaseInterface {
    @Query("My query 1")
    List<MyEntity> getEntities();
}

And another one:

@Repository
@Profile("profile2)
public interface ProfileRepository2 extends RepositoryBaseInterface {
    @Query("My query 2")
    List<MyEntity> getEntities();
}

I have class when I use this repository:

@Service
@RequiredArgConstructor
public class UseRepository{

  RepositoryBaseInterface repository;

  public List<MyEntity> getMyEntities() {
     return repository.getEntities();
  }
}

I have expected when I have one of two active profiles it will be chosen one of two ProfilesRepositories but I see that only RepositoryBaseInterface is using and I recieved error

Error creating bean with name RepositoryBeanInterface
IllegalArgumentException, No property getEntities found for type MyEntity

How can I fix this and use one or another repository in dependency of my active profile?


Solution

  • I understood my mistake. Our Base Interface ought to don't have any extends. But its implementation ought to.

    So I have

        public interface RepositoryBaseInterface {
           List<MyEntity> getEntities();
        }
    

    And two Profile interface:

        @Repository
        @Profile("profile1)
        public interface ProfileRepository extends RepositoryBaseInterface, CrudRepository<MyEntity, Long> {
    
          @Query("My query 1")
          List<MyEntity> getEntities();
    }
    
        @Repository
        @Profile("profile2)
        public interface ProfileRepository2 extends RepositoryBaseInterface, CrudRepository<MyEntity, Long> {
    
          @Query("My query 2")
          List<MyEntity> getEntities();
    }