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?
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);
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With