Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can we use both MongoRepository and MongoTemplate in same application

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.

like image 491
springbootlearner Avatar asked May 05 '18 04:05

springbootlearner


Video Answer


1 Answers

Though MongoRepository is much simpler to use than MongoTemplate, but template 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

  1. Use Repository when you want to use that is already implemented.
  2. Manually implement few custom methods using the mongo-template when you want to implement customMethod which has complex logics.

Implementation

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.

like image 96
Antariksh Avatar answered Jan 01 '23 01:01

Antariksh