Spring boot (VIII) mybatis + docker + mongodb 4 x

1、 Introduction to mongodb

1.1 introduction to mongodb

Mongodb is a powerful, flexible and easy to expand general-purpose database. Mongodb is a document database written in C + +. It has rich functions of relational database, and adds transaction support after 4.0.

With the increasing amount of stored data, developers face a difficulty: how to expand the database? The extended database is divided into horizontal expansion and vertical expansion. Vertical expansion is the use of machines with more powerful computing power. Its disadvantage is that the improvement of machine performance is restricted by physical limits, and mainframes are usually very expensive. Mongodb is designed in the horizontal expansion mode, The document oriented data model makes it easy to segment data on multiple servers. Mongodb can automatically handle the data and load of the cluster and automatically redistribute documents, so that developers can focus on writing applications without considering the problem of expansion.

1.2 mongodb installation

Mongodb can be installed in two ways:

It is recommended to use the second method, which directly uses the mongodb image to install it on docker. The benefits are as follows:

Therefore, this article will focus on the installation and use of mongodb on docker.

If you want to install docker directly on the physical machine, you can check my previous article "Introduction to installation and use of mongodb foundation": https://www.cnblogs.com/vipstone/p/8494347.html

1.3 install mongodb on docker

Installing software on docker generally requires two steps:

1.3. 1 Download Image

To download an image, you need to go to the image Market: https://hub.docker.com/ , if you want to search the software "Mongo", select the official image "official", click Details to get the corresponding download method, and we get the command to download mongodb as follows:

1.3. 2 mount mirror to container

Use command:

Use "docker images" to view the image name and label, as shown below:

After the container is loaded successfully, you can use the Robo 3T client to connect. You do not need to enter a user name and password, as shown in the following figure:

Indicates that the connection has been successful.

Robo 3T is a free database tool for connecting to mongodb, which can be downloaded from the official website: https://robomongo.org/download

1.3. 3. Enable identity authentication

If it is a generation environment, mongodb without user name and password is very insecure, so we need to turn on identity authentication.

Setp1: load container

We still use the downloaded image to reload a container instance. The command is as follows:

Among them "-- auth" is to open identity authentication.

After loading the authentication container successfully, we need to enter the container and set the user name and password for mongodb.

Setp2: enter the container
Setp3: enter Mongo command line mode
Setp4: create user

The created user name is "admin", the password is "admin", and the specified database is "admin".

At this time, we use Robo 3T to input the corresponding information for connection, as shown in the following figure:

Indicates that the connection has been successful.

1.3. 4 create database and set user

Above, we use the system database "admin" with the "admin" account. Usually, we will not directly use the system database in the generation environment. At this time, we need to create our own database and assign corresponding users.

Setp1: you need to enter the container first
Setp2: create database

If there is no testdb, the database will be created automatically.

Setp3: create user assignment database

Among them, the role: "readwrite" table gives users the permission to assign operations and read. Of course, there is no problem in adding indexes and deleting tables.

So far, we can use admin / admin to operate the testdb database.

1.3. 5. Other docker commands

Delete container: docker container RM < container ID / name >

Stop container: docker stop < container ID / name >

Start container: docker start < container ID / name >

Viewing the running container: docker PS

Query all containers: docker PS - A

2、 Mybatis integration mongodb

The spring boot project integrates mybatis. The first two articles have introduced it in detail. I won't introduce it too much here. This article focuses on the integration of mongodb.

Setp1: add dependency

In POM Add the following dependencies to XML:

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

Setp2: configure mongodb connection

In application Properties add the following configuration:

spring.data.mongodb.uri=mongodb://username:pwd@172.16.10.79:27019/testdb

Setp3: create entity class

import java.io.Serializable;

public class User implements Serializable {
    private Long id;
    private String name;
    private int age;
    private String pwd;
	//...略set、get
}

Setp4: create Dao class

import com.hello.springboot.entity.User;
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.data.mongodb.core.query.Update;
import org.springframework.stereotype.Component;
import java.util.List;

@Component
public class UserDao {
    @Autowired
    private MongoTemplate mongoTemplate;
    /**
     * 添加用户
     * @param user User Object
     */
    public void insert(User user) {
        mongoTemplate.save(user);
    }

    /**
     * 查询所有用户
     * @return
     */
    public List<User> findAll() {
        return mongoTemplate.findAll(User.class);
    }

    /**
     * 根据id 查询
     * @param id
     * @return
     */
    public User findById(Long id) {
        Query query = new Query(Criteria.where("id").is(id));
        User user = mongoTemplate.findOne(query,User.class);
        return user;
    }

    /**
     * 更新
     * @param user
     */
    public void updateUser(User user) {
        Query query = new Query(Criteria.where("id").is(user.getId()));
        Update update = new Update().set("name",user.getName()).set("pwd",user.getPwd());
        mongoTemplate.updateFirst(query,update,User.class);
    }

    /**
     * 删除对象
     * @param id
     */
    public void deleteUserById(Long id) {
        Query query = new Query(Criteria.where("id").is(id));
        mongoTemplate.remove(query,User.class);
    }

}

Setp4: create controller

import com.hello.springboot.dao.IndexBuilderDao;
import com.hello.springboot.dao.UserDao;
import com.hello.springboot.entity.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

@RestController
@RequestMapping("/")
public class UserController {
    @Autowired
    private UserDao userDao;

    @RequestMapping("/")
    public ModelAndView index() {
        User user = new User();
        user.setId(new Long(1));
        user.setAge(18);
        user.setName("Adam");
        user.setPwd("123456");
        userDao.insert(user);

        ModelAndView modelAndView = new ModelAndView("/index");
        modelAndView.addObject("count",userDao.findAll().size());
        return modelAndView;
    }
}

Setp5: create page code

<html>
<head>
    <title>王磊的博客</title>
</head>
<body>
Hello ${count}
</body>
</html>

So far, mongodb integration has been completed. Start the project and enter“ http://localhost:8080/ ”Go to the database to view the inserted data.

Insert the database normally, as shown in the figure below:

3、 Mongodb PK auto increment

Careful users may find that although mongodb has been integrated, the user ID is the value of manual set when inserting the database. Next, let's see how to realize the self increment of ID in mongodb.

3.1 implementation ideas

Mongodb implements ID self increment, which is similar to spring boot JPA. It creates a table in the database to record the "self increment ID" of the table. Only by ensuring the atomicity of the added ID and the returned ID each time, it can ensure that the ID realizes the "self increment" function.

3.2 implementation scheme

With the idea, let's look at the specific implementation scheme.

3.2. 1 create entity class

import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;

@Document(collection = "IndexBuilder")
public class IndexBuilder {
    @Id
    private String id;
    private Long seq;
	//..省略get、set方法
}

Where collection = "indexbuilder" refers to the collection name of the database and corresponds to the table name of the relational database.

3.2. 2 create Dao class

import com.hello.springboot.entity.IndexBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoOperations;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Component;
import static org.springframework.data.mongodb.core.FindAndModifyOptions.options;
import static org.springframework.data.mongodb.core.query.Criteria.where;
import static org.springframework.data.mongodb.core.query.Query.query;

@Component
public class IndexBuilderDao {
    @Autowired
    private MongoOperations mongo;
    /**
     * 查询下一个id
     * @param collectionName 集合名
     * @return
     */
    public Long getNextSequence(String collectionName) {
        IndexBuilder counter = mongo.findAndModify(
                query(where("_id").is(collectionName)),new Update().inc("seq",1),options().returnNew(true).upsert(true),IndexBuilder.class);
        return counter.getSeq();
    }
}

3.2. 3. Use the ID of "self increment"

User user = new User();
user.setId(indexBuilderDao.getNextSequence("user"));
//...其他设置

Core code: indexbuilderdao Getnextsequence ("user") uses the ID of "self increment" to realize self increment of ID.

So far, the self adding function of mongodb has been completed. If it is used normally, the database should be as follows:

The indexbuilder of the database is used to record the "self increment ID" of each collection.

Mongodb integration source code: https://github.com/vipstone/springboot-example/tree/master/springboot-mybatis-mongodb

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>