快速入门Springboot使用MongoDB

快速入门Springboot使用MongoDB

第一步:新建Maven工程(比较简单,此步略过)

第二步:新建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);
    }
}

第三步:修改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>

第四步:新建application.yml

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

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

用户名:admin
密码:admin
数据库:hrwy

第五步:新建实体类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 + '\'' +
                '}';
    }
}

第六步:新建接口及实现类

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

第七步:编写测试类

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

在想要测试的接口上写@Test,其他接口上不写@Test,每次保证只测试一个接口。

第八步:确认数据库hrwy已有用户admin,如果没有则需创建用户。

第一步: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"
	]
}

如果完成上述步骤,则可以成功使用springboot对数据库hrwy实现增、删、改、查的基本操作。

如有疑问,请及时留言,加油!

猜你喜欢

转载自blog.csdn.net/A_bad_horse/article/details/109234786
今日推荐