Spring Data : how to use repository's inner interfaces outside the outer class?

Viewed 2444

When I have lot of repositories interface I usually use a wrapper like this :

@Component
public class RepositoryContainer(){

 @Autowired
 public Myrepo1 repo1;

 @Autowired
 public Myrepo2 repo2;
 //and so on....
}

Then I use it :

@Service
public class Myservice(){

 @Autowired
 RepositoryContainer repos;

 public void service1(){
   repos.repo1.findBy...
 }

}

The problem is this way of doing generates many files, since each repository is an interface, so I have same files for repositories as for entities.

To reduce the number of files I tried using nested interfaces :

@Repository
public class RepositoryContainer(){

  public interface Myrepo1 extends JpaRepository<Entity1, Long> {
  }

  public interface Myrepo2 extends JpaRepository<Entity2, Long> {
  }
  //and so on...
}

Now I am struggle because I can't access my repositories outside the class. Is there a way to do this :

@Service
public class Myservice(){

@Autowired
RepositoryContainer repos;

  public void service1(){
  //I would like to do this :
   repos.Myrepo1.findBy...
  }

}

Note that I've already enabled nested discovery repositories in

@EnableJpaRepositories( considerNestedRepositories = true )

Thanks a lot

4 Answers

I support @Cepr0 answer, To reduce your code, you don't have to separate your entities from Repositories interfaces, combine them in one class as follows:-

@Entity
public class MyEntity{
//.....

  @Repository
  public static interface UserRepo extends JpaRepository<MyEntity,String>{

  }
}

then

@SpringBootApplication
@EnableJpaRepositories(considerNestedRepositories = true)
public class Application {
    //...
}

@akuma8 your code can be refactored to remove the extra inner container

@Component
public class RepositoryContainer(){

  @Repository
  public interface Myrepo1 extends JpaRepository<Entity1, Long> {
  }
  @Repository
  public interface Myrepo2 extends JpaRepository<Entity2, Long> {
  }

  public final Myrepo1 repo1;

  public final Myrepo2 repo2;

  @Autowired
  public RepositoryContainer(Myrepo1 repo1, Myrepo2 repo2) {
    this.repo1 = repo1;
    this.repo2 = repo2;
  } 

}
Related