Mongotemplate is the interface between the database and the code, and the operation of the database is within it.
Note: mongotemplate is thread-safe.
Mongotemplate implements the interface mongooperations, it is generally recommended to use Mongooperations for related operations.
New Mongotemplate ( new Simplemongodbfactory (new Mongo (), "Database"));
The mapping between MongoDB documents and domain classes is achieved by implementing Mongoconverter, the interface class.
The default provides two SimpleMappingConverter(default)
andMongoMappingConverter,但也可以自己定义。
How do I create a mongotemplate instance?
1. Via Java code
@Configuration Public class AppConfig { publicthrows Exception { returnnew Mongo ("localhost"); Public throws Exception { returnnew mongotemplate (MONGO (), "MyDatabase"); There are other initialization methods as well. }}
2. Through the XML
<Mongo:mongoHost= "localhost"Port= "27017"/> <BeanID= "Mongotemplate"class= "Org.springframework.data.mongodb.core.MongoTemplate"> <Constructor-argref= "MONGO"/> <Constructor-argname= "DatabaseName"value= "Geospatial"/> </Bean>
Simple examples of Use
Mongooperations Mongoops =NewMongotemplate (NewSimplemongodbfactory (NewMongo (), "database")); Person P=NewPerson ("Joe", 34); //Insert is used to initially store , the object into the database.Mongoops.insert (P); Log.info ("Insert:" +p); //Findp = Mongoops.findbyid (P.getid (), person.class); Log.info ("Found:" +p); //UpdateMongoops.updatefirst (Query (where ("name"). Is ("Joe")), Update ("Age", "+"), person.class); P= Mongoops.findone (Query (where ("name"). Is ("Joe")), person.class); Log.info ("Updated:" +p); //DeleteMongoops.remove (P); //Check that deletion workedlist<person> people = Mongoops.findall (person.class); Log.info ("Number of people =:" +people.size ()); Mongoops.dropcollection (person.class);