Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Autowiring multiple repositories into a single DAO in Spring - bad practice?

Let's say I have the following Spring Mongo repositories. ObjectOne, ObjectTwo and ObjectThree represent documents stored in separate collections within the same database

public interface RepositoryOne extends MongoRepository<ObjectOne, String> {
}

public interface RepositoryTwo extends MongoRepository<ObjectTwo, String> {
}

public interface RepositoryThree extends MongoRepository<ObjectThree, String> {
}

And then a single DAO class

public class ExampleDAO {
    @Autowired
    private RepositoryOne repositoryOne;

    @Autowired
    private RepositoryTwo repositoryTwo;

    @Autowired
    private RepositoryThree repositoryThree;

    //Various methods performing operations with repositoryOne
    //Various methods performing operations with repositoryTwo
    //Various methods performing operations with repositoryThree
}

Is it considered bad practice to be autowiring multiple repositories into a single DAO like above? It feels like the class may be doing too much and ideally I should have a single repository to maintain single responsibility. If it is bad practice, would a separate DAO for each repository be the way to go, or is there a Spring magic way to create a single repository that I can use to call a more specific repository?

like image 520
DraegerMTN Avatar asked Mar 08 '23 00:03

DraegerMTN


1 Answers

Its a bad practice to have multiple unrelated responsibilities for a single class. If they are related consider creating a 'service' class and autowire the repositories. And also the methods in service class can abstract the methods in repositories, for example:

class ExampleService {
    @Autowired
    private RepositoryOne repositoryOne;

    @Autowired
    private RepositoryTwo repositoryTwo;

    void saveEmployee(Employee e) {
        repositoryOne.save(e);
        repositoryTwo.update(e.getEmpId);
    }
}
like image 82
Anil Bachola Avatar answered Mar 09 '23 15:03

Anil Bachola