Quick start Springboot using MongoDB

Quick start Springboot using MongoDB

Step 1: Create a new Maven project (relatively simple, skip this step)

Step 2: Create a new MongoApp.class

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class MongoApp {
    public static void main(String[] args) {
        SpringApplication.run(MongoApp.class, args);
    }
}

Step 3: Modify pom.xml

<?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 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>org.example</groupId>
    <artifactId>mongodb</artifactId>
    <version>1.0-SNAPSHOT</version>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.2.2.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository-->
    </parent>

    <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-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

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

Step 4: Create a new application.yml

配置格式:spring.data.mongodb.uri=mongodb://name:pass@localhost:27017/test

spring:
  data:
    mongodb:
      uri: mongodb://admin:admin@localhost:27017/hrwy

Username: admin
Password: admin
Database: hrwy

Step 5: Create a new entity class UserEntity

package com.mongo.entity;

import java.io.Serializable;

public class UserEntity implements Serializable {
    private static final long serialVersionUID = -3258839839160856613L;
    private Long id;
    private String userName;
    private String password;
    private String type;

    public static long getSerialVersionUID() {
        return serialVersionUID;
    }

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getUserName() {
        return userName;
    }

    public void setUserName(String userName) {
        this.userName = userName;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public String getType() {
        return type;
    }

    public void setType(String type) {
        this.type = type;
    }

    @Override
    public String toString() {
        return "UserEntity{" +
                "id=" + id +
                ", userName='" + userName + '\'' +
                ", password='" + password + '\'' +
                ", type='" + type + '\'' +
                '}';
    }
}

Step 6: Create a new interface and implementation class

package com.mongo.dao;

import com.mongo.entity.UserEntity;

import java.util.List;

public interface UserDao {
    void saveUser(UserEntity user);
    List<UserEntity> findUserByType(String type);
    List<UserEntity> findUserByCollection(String CollectionName,String type);
    UserEntity findUserByUserName(String userName);
    void updateUser(UserEntity user);
    void deleteUserById(Long id);
}
package com.mongo.dao.impl;

import com.mongo.dao.UserDao;
import com.mongo.entity.UserEntity;
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 UserDaoImpl implements UserDao {
    @Autowired
    private MongoTemplate mongoTemplate;

    /**
     * 创建对象
     * @param user
     */
    public void saveUser(UserEntity user) {
        mongoTemplate.save(user);
    }

    public List<UserEntity> findUserByType(String type) {
        Query query=new Query(Criteria.where("type").is(type));
        List<UserEntity> userlist =  mongoTemplate.findAllAndRemove(query , UserEntity.class);
        return userlist;
    }

    public List<UserEntity> findUserByCollection(String CollectionName,String type) {
        Query query=new Query(Criteria.where("type").is(type));
        List<UserEntity> userlist =  mongoTemplate.findAllAndRemove(query , UserEntity.class,CollectionName);
        return userlist;
    }

    /**
     * 根据用户名查询对象
     * @param userName
     * @return
     */
    public UserEntity findUserByUserName(String userName) {
        Query query=new Query(Criteria.where("userName").is(userName));
        UserEntity user =  mongoTemplate.findOne(query , UserEntity.class);
        return user;
    }

    /**
     * 更新对象
     * @param user
     */
    public void updateUser(UserEntity user) {
        Query query=new Query(Criteria.where("id").is(user.getId()));
        Update update= new Update().set("userName", user.getUserName());
        //更新查询返回结果集的第一条
        mongoTemplate.updateFirst(query,update,UserEntity.class);
        //更新查询返回结果集的所有
        // mongoTemplate.updateMulti(query,update,UserEntity.class);
    }

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

Step 7: Write test class

package com.mongo;

import com.mongo.dao.UserDao;
import com.mongo.entity.UserEntity;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(classes = MongoApp.class)
public class MongoTest {
    @Autowired
    UserDao userDao;

    public void testSaveUser() throws Exception {
        UserEntity user=new UserEntity();
        user.setId(1024);
        user.setUserName("张三");
        user.setType("C");
        userDao.saveUser(user);
    }

    public void findUserByUserName(){
        UserEntity user= userDao.findUserByUserName("张三");
        System.out.println("user is "+user);
    }

    public void updateUser(){
        UserEntity user=new UserEntity();
        user.setId(1024);
        user.setUserName("李四");
        userDao.updateUser(user);
    }

    @Test
    public void deleteUserById(){
        userDao.deleteUserById(1024);
    }
}

Write @Test on the interface you want to test, and don’t write @Test on other interfaces. Make sure to test only one interface at a time.

Step 8: Confirm that there is a user admin in the database hrwy, if not, create a user.

第一步:use hrwy; // 切换至数据库hrwy

第二步:show users // 显示数据中已有的用户

第三步:创建用户admin
db.createUser({ user: 'admin', pwd: 'admin', roles: [ { role: "root", db: "admin" } ] });

第四步:查看用户信息
> show users
{
	"_id" : "hrwy.admin",
	"userId" : UUID("c907c65a-067e-47e3-b264-941ba8c5542c"),
	"user" : "admin",
	"db" : "hrwy",
	"roles" : [
		{
			"role" : "root",
			"db" : "admin"
		}
	],
	"mechanisms" : [
		"SCRAM-SHA-1",
		"SCRAM-SHA-256"
	]
}

If you complete the above steps, you can successfully use springboot to implement the basic operations of adding, deleting, modifying, and checking the database hrwy.

If you have any questions, please leave a message in time and come on!

Guess you like

Origin blog.csdn.net/A_bad_horse/article/details/109234786