发表于 2015-7-9 08:44:54

[Spring Data MongoDB]学习笔记--牛逼的MongoTemplate

  MongoTemplate是数据库和代码之间的接口,对数据库的操作都在它里面。
  注:MongoTemplate是线程安全的。
  MongoTemplate实现了interface MongoOperations,一般推荐使用MongoOperations来进行相关的操作。



MongoOperations mongoOps = new MongoTemplate(new SimpleMongoDbFactory(new Mongo(), "database"));
  
  MongoDB documents和domain classes之间的映射关系是通过实现了MongoConverter这个interface的类来实现的。
  默认提供了两个SimpleMappingConverter(default) 和 MongoMappingConverter,但也可以自己定义。
  
  如何创建一个MongoTemplate实例?
  1. 通过java code



@Configuration
public class AppConfig {
public @Bean Mongo mongo() throws Exception {
return new Mongo("localhost");
}
public @Bean MongoTemplate mongoTemplate() throws Exception {
return new MongoTemplate(mongo(), "mydatabase");//还有其它的初始化方法。
}
}
  2. 通过xml








  
  使用的简单例子



MongoOperations mongoOps = new MongoTemplate(new SimpleMongoDbFactory(new Mongo(), "database"));
Person p = new Person("Joe", 34);
// Insert is used to initially store the object into the database.
    mongoOps.insert(p);
log.info("Insert: " + p);
// Find
p = mongoOps.findById(p.getId(), Person.class);   
log.info("Found: " + p);
// Update
mongoOps.updateFirst(query(where("name").is("Joe")), update("age", 35), Person.class);   
p = mongoOps.findOne(query(where("name").is("Joe")), Person.class);
log.info("Updated: " + p);
// Delete
    mongoOps.remove(p);
// Check that deletion worked
List people =mongoOps.findAll(Person.class);
log.info("Number of people = : " + people.size());

mongoOps.dropCollection(Person.class);
  
页: [1]
查看完整版本: [Spring Data MongoDB]学习笔记--牛逼的MongoTemplate