[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
<mongo:mongo host="localhost" port="27017"/> <bean id="mongoTemplate" class="org.springframework.data.mongodb.core.MongoTemplate"> <constructor-arg ref="mongo"/> <constructor-arg name="databaseName" value="geospatial"/> </bean>
使用的简单例子
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<Person> people = mongoOps.findAll(Person.class); log.info("Number of people = : " + people.size()); mongoOps.dropCollection(Person.class);