Question about Repository pattern
Is it 'wrong' to call 2 different databases in a repository? For example I have this interface
public interface PostRepository {
Post findById(int id);
Collection<Post> findAll();
Collection<Post> search(Map<String, String> Query);
}
and then an implementation that uses SQL database for the first two, and then something like ElasticSearch/Solr for the search method lets say for example SqlSolrPostRepository
public class SqlSolrPostRepository {
@Inject private SolrClient solrClient;
@Inject private Connection sqlConnection;
public Post findById(int id) {
// Get Post from SQL database
}
public Collection<Post> findAll() {
// Get all Posts from SQL database
}
public Collection<Post> search(Map<String, String> Query) {
// Build a SolrQuery from the given map
// Run the Solr Query
// Return the matching Posts
}
}
How should I do it? Should I create a seperate SearchService Interface and create a Solr implementation for it. If so, would you call the SearchService from the repository? Or call the searchservice from the client code? looking for some advice :)
Posted Jan 14, 2016, 7:37 AM UTC
33
I would keep them seperate, the point of a repository is to abstract away a specific data access implementation. Mixing SQL and Solr would be giving the repo two responsibilities.
I would indeed have a SearchService, but I would make it a class, not an interface. It's ok to have service classes that are stateless and injectable. SearchService would taken in a PostRepository and SearchRepository interface. I would remove search from the Postrepository if you dont want to support SQL searches and only rely on solr.
Hey, thanks for your ideas. I also think im better off separating the searching from the repository.
Why would you not have an SearchService interface and then a SolrSearchService implementation? Otherwise my application would be coupled to just Solr and changing the search backend would become harder if you wanted to ever do that.
Then a little offtopic: any tips on building a Solr query string from a html form ("foo:bar AND baz:qux") in a Stripes application? At the moment I'm putting the form data into a Map<String, String> then join and escape them accordingly in the searchservice class.
You are correct I didn't mean to imply that SearchService will coupled to Solr. Instead it's a middle tier between your application and the implmentation for example
UI -> SearchService Class(SearchRepository(interface), PostReposoitory(interface)
SearchRepository would be an interface, the implementation would be Solr. SearchService just makes a call to SearchRepository.
Here is a similar thing but in C# https://dotnetfiddle.net/Z32Fhj