I am struggling to understand how to best query a repository.
The three factors that are throwing me through a loop right now are:
- Return type of data
- Columns to run query on
- Number of records to return
Point 1
In regards to question one:
I have Repositories with lot of methods that return a combination of both Entities and scalar values. This seems to lead to "method explosion". Should I always return an Entity object? How should I query for objects where I only need one column?
Point 2 When running a query should I include every column in the table even if I only need one, or two columns? If I create specific queries for this it leads to more methods in the Repository
Point 3 How should I provide conditions for the query? I read about Specifications, but my understanding is that you loop through the returned records and filter out the ones that pass into a new collection. This doesn't seem like a good idea performance wise. Right Now I just make a new method in the Repo like getNameById() which encapsulates the condition.
Please not that I am not using an ORM, I just have raw sql in my Repositories.
Update
Point 1: Based on the answers and a bit more research would this be a good implementation?
Right now I have a large repository that return a mix of scalar and entity type objects (all same entity). I'm thinking I could reduce this greatly if I just use a GetUser(userId) method and forget writing methods that just return single column values.
For example if I need to return a user name I could call the GetUser(userId) method that hydrates the User object and then in the service layer just filter it down to the username.
Another way would be to use some sort of QueryBuilder class I could pass into the Repository which could be parsed to generate the proper sql.
Point 2
Looking back this is pretty similar to point one and my current solution would be to just grab all table fields. It's a tradeoff between performance and maintainability.
Point 3
I would need to provide some sort of where clause. I'm not sure if this make sense doing via Specification or just a sql string. My current solution is to make new methods for these types, but I would like something more generic for the Repository
Overall, still researching into this... I'd love to hear more input into this or links to books or references that kind of tie this all together.