Reputation: 1380
I need to write some complex query on MongoDB and some simple queries.Can I use MongoRepository for simple queries and MongoTemplate along with Query or Criteria for complex query implementation same application.
Is it good design using both MongoTemplate and MongoRepositories in same applications. Is there any drawback of this approach.
Also what is the best approach to write complex queries with lot of predicate which involves and,or,IN and Not In in single query.
Upvotes: 7
Views: 6506
Reputation: 518
Although MongoRepository is much simpler to use than MongoTemplate, MongoTemplate gives you more fine grained control over the queries that you're implementing.
Having said that you can still be implementing complex queries on using MongoRepository like this:
@Query("{'id': ?#{ [0] ? {$exists :true} : [1] }}")
List<Person> findByQueryWithExpressionAndNestedObject(boolean param0, String param1);
More information on can be found here
But as a practise it's actually good to have both in your code, that is
mongo-template
when you want to implement customMethod which has complex logics.Step 1:
interface CustomEmployeeRepository{
List<Employee> CustomEmployeeMethod(String field)
}
Step 2 :
@Repository
public class CustomEmployeeRepositoryImpl implements CustomEmployeeRepository{
@Autowired
private MongoTemplate mongotemplate;
@Override
List<Employee> CustomEmployeeMethod(String field){
}
}
Step 3:
Now create a new repository extending MongoRepository
and CustomEmployeeRepository
to use the custom implementations as well as predefined methods of repository.
interface EmployeeRepository extends MongoRepository<Employee, long>, CustomEmployeeRepository{
}
This way you get the best of both world. Refer to the documentation for more information on the implementation. Hope this helps.
Upvotes: 13