1

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:

But the solution is in using conventions of class names. Is there any way to make it by class design?

Community
  • 1
  • 1
Andrii Abramov
  • 10,019
  • 9
  • 74
  • 96
  • I don't think you can make aggregate queries through `UserRepository` out of box. You can autowire mongo template into user repository if you wanted to keep everything in one place. – s7vr Jan 07 '17 at 14:29
  • @SagarReddy you are right. I can't. The question is how to `@Autowire` it into implementation of `UserRepository`? (If I will declare necessary methods there – Andrii Abramov Jan 07 '17 at 14:34

0 Answers0