使用java注释的mongo存储库基础包

时间:2016-12-14 07:26:07

标签: java spring mongodb

@EnableMongoRepositories(basePackages = "com.jcg.examples.repo")
public class Application {
    @Autowired
    PersonRepo personRepo;
    @Autowired
    AddressRepo addressRepo;

    public void main() throws UnknownHostException {

        try {
            //for mongoTemplate access
            Mongo mongo = new Mongo("www.host", port);
            UserCredentials credentials = new UserCredentials("username", "password");
            MongoTemplate mongoTemplate = new MongoTemplate(mongo, "DbName", credentials);


            System.out.println("connect to database successfully");
            Set<String> collectionsName = mongoTemplate.getCollectionNames();
            System.out.println("Collections Names ###########");
            for (String str : collectionsName) {
                System.out.println(str);
            }
            Person personAchilles = new Person();
            personAchilles.setPersonId(1l);
            personAchilles.setName("Achilles");
            personAchilles.setAge(50);
            personRepo.save(personAchilles);

            Person personHektor = new Person();
            personHektor.setPersonId(2l);
            personHektor.setName("Hektor");
            personHektor.setAge(60);

            Address address = new Address(1, "221b Baker Street", "London NW1", "London", 12345l);
            List<Address> addresses = personHektor.getAddresses();
            addresses.add(address);
            //.......persist data........
            addressRepo.save(address);
            personRepo.save(personHektor);

            //........List data......
            Iterable<Person> personList = personRepo.findAll();
            System.out.println("Person List : ");
            for (Person person : personList) {
                System.out.println(person);
            }
            //........filter data.......                    
            System.out.println("Person with Id 1 is " + personRepo.searchByName("Achilles"));

            context.close();
        } catch (BeansException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        //              context.close();

    }
}

执行时,MongoDB连接工作正常并从集合中获取记录,但在Mongo中使用repo类仍然无效。

请帮我用Java注释解决这个问题。我们没有使用XML配置。

0 个答案:

没有答案