Spring Boot from entry to the master (j) to read and write MongoDB integration of non-relational databases

Source: plain text house blog

Address: https://blog.yoodb.com/yoodb/article/detail/1578

MongoDB is an open source NoSQL document database. It can store a variety of data structures, similar to the BSON JSON, complex data types can be stored.

Spring Boot using MongoDB provides many benefits, including spring-boot-starter-data-mongodb 'Starter POM'. In this paper to learn about the integration of Spring Boot MongoDB database, be implemented in different ways to read and write MongoDB database, namely the new interface and the interface class to achieve MongoRepository MongoTemplate class two methods directly.

The biggest feature is support for MongoDB query language is very powerful, its syntax is similar to the object-oriented way, you can achieve most of the functionality is similar to single-table query relational databases, but also support for data indexing.

Download and install MongoDB start

1, MongoDB download https://www.mongodb.com/download-center/community?jmp=docs

As shown in FIG Reference:

2, download mongodb-win32-x86_64-2012plus-4.2.5.zip file compression package, for example, after unzip the file directory as follows:

3, the service start MongoDB 1) using the switch command cmd directory, run the following command:

cmd E:\tools\mongodb-win32-x86_64-2012plus-4.2.5\mongodb-win32-x86_64-2012plus-4.2.5\bin

  

2) start the MongoDB service, execute the following command:

mongod --dbpath E:\software\MongoDB\data

  


4, start to see the situation

Enter your browser to http: // localhost: 27017 (27017 is mongodb port number) to see if the show:

The connection is successful, otherwise unsuccessful, you can see if the port is occupied.

Configuration files and entity classes

1, pom.xml file

Add spring-boot-starter-data-mongodb incorporated mongodb support access to the file in the pom.xml dependency, its implementation depends spring-data-mongodb, the configuration information is as follows:

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-mongodb</artifactId>
</dependency>

  

The project case pom.xml file configuration information is as follows:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>2.2.5.RELEASE</version>
		<relativePath/>
	</parent>
	<groupId>com.yoodb.study.demo06</groupId>
	<artifactId>springboot-study-demo06</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<packaging>war</packaging>
	<name>springboot-study-demo06</name>
	<description>Demo project for Spring Boot</description>

	<properties>
		<java.version>1.8</java.version>
	</properties>

	<dependencies>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-data-mongodb</artifactId>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-web</artifactId>
		</dependency>

		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-tomcat</artifactId>
			<scope>provided</scope>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-test</artifactId>
			<scope>test</scope>
			<exclusions>
				<exclusion>
					<groupId>org.junit.vintage</groupId>
					<artifactId>junit-vintage-engine</artifactId>
				</exclusion>
			</exclusions>
		</dependency>
	</dependencies>

	<build>
		<plugins>
			<plugin>
				<groupId>org.springframework.boot</groupId>
				<artifactId>spring-boot-maven-plugin</artifactId>
			</plugin>
		</plugins>
	</build>
</project>

  

2, the data source configuration

Increase in application.properties file reads as follows:

# mongodb 配置
spring.data.mongodb.uri=mongodb://localhost:27017
spring.data.mongodb.database=selection

  

3, write BootUser entity object

BootUser MongoDB database table corresponding to the class file attribute value field, specific code as follows:

package com.yoodb.study.demo06.entity;

import java.io.Serializable;

public class BootUser implements Serializable {

    private String id;
    private String name;
    private String detail;
	
    public String getId() {
        return id;
    }
    public void setId(String id) {
        this.id = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getDetail() {
        return detail;
    }
    public void setDetail(String detail) {
        this.detail = detail;
    }
}

  

MongoDB read and write

A mode: MongoRepository Interface 1, interface class file UserRepository define new interfaces and inheritance MongoRepository repository interfaces, specific code as follows:

package com.yoodb.study.demo06.repository;

import com.yoodb.study.demo06.entity.BootUser;
import org.springframework.data.mongodb.repository.MongoRepository;
import org.springframework.stereotype.Service;

@Service
public interface UserRepository extends MongoRepository<BootUser, String> {

   public BootUser save(BootUser user);

}

  

Note: The definition of interface inheritance MongoRepository class in Spring Boot Framework query if some of the data, only need to write an interface name and the corresponding parameters can be in accordance with the format.

2, define an interface class file UserService , specific code as follows:

package com.yoodb.study.demo06.service;

import com.yoodb.study.demo06.entity.BootUser;
import org.springframework.stereotype.Repository;

@Repository
public interface UserService {

    public void save(BootUser user);
}

  

3, to realize a new class file UserServiceImpl UserService interface class , specific code as follows:

package com.yoodb.study.demo06.service.impl;

import com.yoodb.study.demo06.entity.BootUser;
import com.yoodb.study.demo06.repository.UserRepository;
import com.yoodb.study.demo06.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserRepository userRepository;

    public void save(BootUser user) {
        userRepository.save(user);
    }
}

  

4, the new class file HelloWorldController , specific code as follows:

 

package com.yoodb.study.demo06;

import com.yoodb.study.demo06.entity.BootUser;

import com.yoodb.study.demo06.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class HelloWorldController {

    @Autowired
    private UserService userService;
       
    @RequestMapping("save")
    public boolean save(){
        // insert data 
        BootUser the User = new new BootUser (); 
        user.setId ( "003"); 
        user.setName ( "plain text house blog"); 
        user.setDetail ( "003 Watch" Java featured "micro-channel public number, together progress ");! 
        mongotemplate.save (the User); 
        return to true; 
    } 

}

  

5, start the project visit the following address:

http://localhost:8080/save

Returned the following results:

true

  

MongoDB stored data to a database, as shown:

Second way: Using MongoTemplate

1, Spring Boot automatically injected mongotemplate , this relatively simple manner directly before HelloWorldController new class file, add code as follows:

package com.yoodb.study.demo06;

import com.yoodb.study.demo06.entity.BootUser;

import com.yoodb.study.demo06.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class HelloWorldController {

    @Autowired
    private UserService userService;

    @Autowired
    private MongoTemplate mongotemplate;
       
    @RequestMapping ( "Save") 
    public Boolean Save () { 
        // insert data 
        BootUser new new BootUser = User (); 
        user.setId ( "003"); 
        user.setName ( "plain text blog home"); 
        user.setDetail ( "003 concerned" Java featured "micro-channel public number, progress together!"); 
        mongotemplate.save (the User); 
        return to true; 
    } 

    @ RequestMapping ( "the SELECT") 
    public String the SELECT (String the above mentioned id) { 
        // query data 
        query query new new Query = (); 
        query.addCriteria (Criteria.where ( "ID") IS (ID).); 
        String Detail mongotemplate.findOne = (Query, BootUser.class) .getDetail (); 
        return Detail; 
    } 

}

  

2, start the project

Visit the following address:

http://localhost:8080/select?id=001

Returned the following results:

001 Watch "Java featured" micro-channel public number, progress together!

 

This article article source project (springboot-study-demo06) Address:

https://github.com/yoodb/springboot

This two ways about Spring boot integrate MongoDB read and write non-relational databases on the finish, and subsequent Spring Cloud series also continued to update, you can browse the collection easy to learn later reference. Here we have time, then you can give it a try, what questions please leave a message below.

Guess you like

Origin www.cnblogs.com/MrYoodb/p/12571821.html