[Spring Data MongoDB] learning notes-awesome MongoTemplate and mongodb integration with spring
The operation template is an interface between the database and the Code. All operations on the database are in it.
Note: Producer template is thread-safe.
Using template implements interface operations. It is generally recommended to use operations for related operations.
MongoOperations mongoOps = new MongoTemplate(new SimpleMongoDbFactory(new Mongo(), "database"));
The MongoDB ing between MongoDB documents and domain classes is achieved by implementing the MongoConverter interface class.
TwoSimpleMappingConverter(default)
AndMongoMappingConverter, but you can also define it yourself.
How to Create a template instance?
1. Use java code
@ Configurationpublic class AppConfig {public @ Bean Mongo mongo () throws Exception {return new Mongo ("localhost");} public @ Bean jsontemplate () throws Exception {return new jsontemplate (mongo (), "mydatabase"); // other initialization methods are available. }}
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>
Simple Example
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);
Which jar package does orgspringframeworkdatadocumentmongodbworkflow template belong?
This is a mongoDB package. You can go to the next one on the official website. The addresses of the latest template in M2 and M4 versions are different. You can try it yourself.
Teach Spring Data Mongodb auto-incremental ID implementation
You have to find a place to find the current number of IDs, and then query each insert operation, and add after insert.