Spring Data MongoDB: set repository collection?

autowired, mongodb, spring

Solution

This part of the docs may have the answer you're looking for:

http://static.springsource.org/spring-data/data-mongodb/docs/current/reference/html/#mongo-template.save-insert.collection

There are two ways to manage the collection name that is used for operating on the documents. The default collection name that is used is the class name changed to start with a lower-case letter. So a com.test.Person class would be stored in the "person" collection. You can customize this by providing a different collection name using the @Document annotation. You can also override the collection name by providing your own collection name as the last parameter for the selected MongoTemplate method calls.

Problem

how do I specify the collection I want my repository to be of? My configuration: ``` <!-- Database --> <mongo:mongo id="mongoDb" host="localhost" port="27017"/> <mongo:db-factory id="mongoDbFactory" mongo-ref="mongoDb" dbname="test"/> <bean id="mongoTemplate" class="org.springframework.data.mongodb.core.MongoTemplate"> <constructor-arg name="mongoDbFactory" ref="mongoDbFactory"/> </bean> <mongo:repositories base-package="de.cochu.springtest.mongodb.repositories"/> ``` My document: ``` @Document public class User { @Id String id; @Indexed String email; ...getters and setters omitted... } ``` the repository for the user-collection (is inside the ...mongodb.repositories package). I extended from the CrudRepository: ``` public interface UserRepository extends CrudRepository<User, String>{ User findByEmail(String email); } ``` and finally, a controller of my spring servlet in which I want to use the UserRepository: ``` @Controller public class MyController { @Autowire UserRepository repo; @RequestMapping("/test.html") public String something(HttpServletRequest request) { User u = userRepository.findByEmail(request.getParameter("email")); ... } } ``` I set up some example users via console, the mongoTemplate.getCollection("users").count() works fine. The repository finds nothing. ... how does the UserRepository know that I want to search the users in the collection "users" ?/Is this the right way to use the repositories? ... Intellij IDEA does not recognize the autowiring of the UserRepository. Although it displays an error, it compiles and throws no exception. Is there something I can do about that?

Original source