0

I am writing a micro-service that should work with multiple database.
For example, assume project A is working with MongoDB, then my service should know how to connect and work (querying, saving, etc...) with MongoDB (or any other SQL database).

I have read this document written by Oracle explaining the DAL and DAO models, but as I understand, I need to implement every method for every kind of query that I would like to execute.

For example, let's say I have this class:

public class Account {

 private String userName;
 private String firstName;
 private String lastName;
 private String email;
 private int age;

}

As concluded from the link above, for every query that I want to execute I need to write a function in the DAO interface (like a db gateway), i.e:

getAccountByEmail(...)
getAccountByUsername(...)
getAccountByUsernameAndEmail(...)

This seems to me like a bad approach which will result in too much methods to handle.
There are also query fields the model does not contain. For instance, if my model has a creation date and I want to query the object in between two dates, I need a way to query the DB for those fields.

I have been looking around for a while now, but I couldn't find a guide or a best practice to approach this problem.
I would like to know if there is any other way to solve this but implementing every method.

1
  • If you are looking for some ready to eat meal then consider using Spring-data (projects.spring.io/spring-data). Commented Jun 7, 2016 at 13:32

1 Answer 1

1

As Appolo mentioned in the comment, Spring Data Mongo DB might solve one of your problem that you don't have to implement each method. However, you still may require declare the method in the interface. Using Spring Data Mongo DB, you first have to define the interface (not class) which should extend MongoRepository. Assumed your primary id is String Eg:

public Interface AccountDAO extends MongoRepository<Account, String> {
    Account getAccountByEmail(String email);
    Account getAccountByUserName(String userName);
}

Remember, the word after 'By' in the method should match the field in your Model. Also you can combine multiple fields using 'And'.

Account getAccountByUserNameAndEmail(String userName, String email);

You can find the supported key words for query in MongoDb Spring data documentation. If you want additional methods which you can't find implementation in Spring Data Mongo DB, you implement your interface and override them.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.