[Spring Data MongoDB] Learning notes--mongotemplate

Source: Internet
Author: User

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);

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.