Spring boot Connect and manipulate MongoDB

Source: Internet
Author: User
Tags findone mongodb mongodb connection string port number spring initializr

Spring Boot is a further encapsulation of spring, designed to simplify the installation and configuration of spring. We know that using spring to build a project environment often involves referencing many jar packages and creating a lot of XML files as the business becomes more complex. Spring boot encapsulates many of the service components of spring integration and automatically creates instances of those objects, and you can quickly build a development environment by simply introducing the jar packages of the serviced components that you need to use.
The service components that Spring boot integrates can be found on the website, and you can tick the service components you use and download the appropriate MAVEN project locally.
Spring boot also integrates support for nosql such as MongoDB, which is described below with spring boot connection and manipulation of MongoDB. Create a Spring boot project

The IDE used in this article is idea, and its spring INITIALIZR is a quick visual component for creating a spring boot project, but you can also build a MAVEN project and introduce the relevant POM on the Spring boot website.
Create a new spring boot project, enter the Spring boot component auto-configuration URL, and click Next.

Enter information about the purpose of the MAVEN entry and select the JDK version.

Select the service component you want.

The Created Spring Boot project is an empty MAVEN project with the required jar packages in the POM. Spring Boot Connection MongoDB

Spring data provides support for operating multiple databases, with simple APIs and easy invocation. We use spring data for MONGODB connections. Here are two ways to connect to MongoDB. Spring Boot intends to simplify or even eliminate the XML configuration of the native spring framework, so the Spring boot project advocates not using XML configuration files for bean management as much as possible. The first approach is to use properties for the connection configuration of MongoDB

For MongoDB connection string configuration in Application.properties, Org.springframework.boot.autoconfigure.mongo provides configuration support for MongoDB connection strings. We configure the specified properties.
Note that the following configuration is not supported for MONGO 2.4 or later.

spring.data.mongodb.host=127.0.0.1
spring.data.mongodb.port=27017
spring.data.mongodb.username=root
spring.data.mongodb.password=root
Spring.data.mongodb.database=gis

2.4 or later use the following connection configuration:

Spring.data.mongodb.uri=mongodb://root (userName): root (password) @localhost (IP address): 27017 (port number)/gis (collections/database )

Create a database operations test class.

@Component public class Dbdaotest {@Autowired private mongotemplate mongotemplate;
    public void Save (Polygon Polygon) {mongotemplate.save (Polygon); } public void Saveregions (list<gisregion> gisregionlist) {Mongotemplate.insert (gisregionlist,gisregion.
    Class); } public <T> T FindByID (class<t> entityclass, String ID) {return Mongotemplate.findbyid (ID, Enti
    Tyclass); } public <T> list<t> findAll (class<t> entityclass) {return Mongotemplate.findall (ENTITYCLA
    SS);
    } public <T> void remove (T entity) {Mongotemplate.remove (entity);
    } public <T> void Add (T entity) {Mongotemplate.insert (entity);
    } public <T> void AddAll (list<t> entity) {Mongotemplate.insertall (entity);
    } public <T> void Saveorupdate (T entity) {Mongotemplate.save (entity); } public <T> T FindOne (class<t> ENtityclass) {return Mongotemplate.findone (new Query (), entityclass); } public list<polygon> findintersective (GeoJson GeoJson) {query query=new query (Criteria.where ("Geometr
        Y "). intersects (GeoJson));
        List<polygon> List=mongotemplate.find (Query,polygon.class);
    return list; The public boolean isexistintersective (GeoJson GeoJson) {query query=new query (criteria.where ("geometry"). Inter
        Sects (GeoJson). and ("_id"). is (100000));
        Boolean res=mongotemplate.exists (Query,gisregion.class);
    return res; }

}

The Mongotemplate class of the Org.springframework.data.mongodb.core package provides all the operation methods for MongoDB and automatically assembles the Mongodbfactory class object connected to the database, which we application.prop Erties defines the parameters required for the Mongodbfactory object, spring boot automatically helps us create the object for mongotemplate use, and if we do not specify a connection string, spring When boot automatically assembles mongotemplate objects in @autowired, the 127.0.0.1:27017 address, test database, and no password access are used by default.
For more information on how to operate your database, see the Mongotemplate class for details. The second way is to create a configuration class for the connection configuration of MongoDB

Create a new Database.properties file under the Maven Resource folder and define the database connection string.

mongodb.uri=127.0.0.1:27017
mongodb.username=root
mongodb.password=root
Mongodb.schema=gis

Consider the fact that the environment is often switched during the actual development of the project, so you can take the option of referencing external configuration parameters, and Spring boot uses the @...@ placeholder to specify the external parameters in the Propertis file. Define the external parameters in the Pom file profile for the Propertis file reference. The profile file for Pom.xml is configured as follows:

<project> ...

    <profiles>
        <profile>
            <id>dev</id>
            <activation>
                < activebydefault>true</activebydefault>
            </activation>
            <properties>
                < Db.mongo.server>127.0.0.1:27017</db.mongo.server>
                <db.mongo.schema>gis</db.mongo.schema >
                <db.mongo.user>root</db.mongo.user>
                <db.mongo.password>root</ db.mongo.password>
            </properties>
        </profile>
    </profiles>

</project >

Database.properties file:

#mongodb. uri= @db. mongo.server@
#mongodb. username= @db. mongo.user@
#mongodb. password=@ db.mongo.password@
#mongodb. schema= @db. mongo.schema@

Create the Mongodbconfig class and instantiate the Mongodbfactory bean:

@Configuration  //is equivalent to configuring the bean
@PropertySource in XML (value = "Classpath:database.properties", Ignoreresourcenotfound = True) public
class Mongodbconfig {
    @Value ("${mongodb.schema}")
    private String DatabaseName;

    @Value ("${mongodb.uri}")
    private String URI;

    @Value ("${mongodb.username}")
    private String username;

    @Value ("${mongodb.password}")
    private String password;

    @Bean public
    mongodbfactory mongodbfactory () throws unknownhostexception {
        String uristr= "mongodb://" + Username+ ":" +password+ "@" +uri+ "/" +databasename;
        System.out.println (URISTR);
        Mongoclienturi mongoclienturi=new Mongoclienturi (URISTR);
        Mongodbfactory mongodbfactory=new simplemongodbfactory (Mongoclienturi);
        return mongodbfactory;
    }
}

The spring framework uses the Mongodbfactory bean when the @autowired automatically assembles the mongotemplate.

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.