I need to make some aggregation using MongoTemplate
.
I am using Spring Data MongoDB, so most of my CRUD operations are made through MongoRepository
interface. I have read about @NoRepositoryBean
but I don't know how to use it in my case.
// UserRepository.java
// imports omitted
@Repository
public interface UserRepository extends MongoRepository<User, String> {
User findOneByUsername(String username);
@Query(value = "{ '_id' : ?0 }", fields = "{ 'username' : 1 }")
User getUserDetails(String userId);
}
// CustomUserRepo.java
// imports omitted
@Component
public class CustomUserRepo {
@Autowired
private final UserRepository userRepository;
public List<Todo> getUserTodos(String userId){
TypedAggregation<User> aggregation = newAggregation(
User.class, Aggregation.match(Criteria.where("_id").is(userId)),
Aggregation.unwind("todos")
);
AggregationResults<Todo> groupResults = mongoTemplate.aggregate(aggregation, User.class, Todo.class);
return groupResults.getMappedResults();
}
}
How to make it as the same UserRepository
bean?
If I inherit UserRepository
I have to implement all methods.
If I make CustomUserRepo
abstract it can't be instantiated.
Update:
Useful articles:
- What's the difference between Spring Data's MongoTemplate and MongoRepository?
- No property found for type error when try to create custom repository with Spring Data JPA
But the solution is in using conventions of class names. Is there any way to make it by class design?