gpt4 book ai didi

Springboot连接NoSQL数据库MongoDB,读取集合数据文档

转载 作者:知者 更新时间:2024-03-13 08:50:36 26 4
gpt4 key购买 nike

这里有MongoDB搭建配置和启动介绍:

MongoDB数据库开发环境搭建与配置,Windows环境下_Zhang Phil-CSDN博客MongoDB是一种NoSQL数据库。本文以Windows环境为例搭建配置MongoDB。MongoDB下载链接:MongoDB Community Download | MongoDBhttps://www.mongodb.com/try/download/community解压后,可以看到在\bin目录下有两个.exe文件,mongo.exe和mongod.exe。mongo.exe是连接MongoDB数据库的客户端,mongod.exe是服务器端程序。(1)启动MongoDB服务器端。

https://blog.csdn.net/zhangphil/article/details/122453754

下面是在spring boot里面载入MongoDB,然后读取MongoDB的集合数据(基于上面文章创建的MongoDB数据库和集合)。

前提是启动MongoDB数据库:

mongod --dbpath=d:/mongodb/data

(1)写一个类,此类对应MongoDB里面集合的文档:

import org.springframework.data.mongodb.core.mapping.Document;
import org.springframework.data.mongodb.core.mapping.FieldType;
import org.springframework.data.mongodb.core.mapping.MongoId;

import java.util.List;

@Document
public class Person {
    @MongoId(value = FieldType.OBJECT_ID)
    private String id;

    private String name;
    private String city;
    private String age;
    private List it;

    public Person() {

    }

    public Person(String id, String name, String city, String age, List it) {
        this.id = id;
        this.name = name;
        this.city = city;
        this.age = age;
        this.it = it;
    }

    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 getCity() {
        return city;
    }

    public void setCity(String city) {
        this.city = city;
    }

    public String getAge() {
        return age;
    }

    public void setAge(String age) {
        this.age = age;
    }

    public List getIt() {
        return it;
    }

    public void setIt(List it) {
        this.it = it;
    }

    @Override
    public String toString() {
        return "{" +
                "id='" + id + '\'' +
                ", name='" + name + '\'' +
                ", city='" + city + '\'' +
                ", age='" + age + '\'' +
                ", it=" + it +
                '}';
    }
}

(2)定义Person的存储访问接口:

import org.springframework.data.mongodb.repository.MongoRepository;
import org.springframework.stereotype.Repository;

@Repository
public interface PersonRepository extends MongoRepository<Person, String> {

}

完成PersonRepository的实现:

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.repository.query.FluentQuery;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Optional;
import java.util.function.Function;

@Component
public class PersonRepositoryImpl implements PersonRepository {
    @Autowired
    private MongoTemplate mongoTemplate;

    private final String COLLECTION_NAME = "zhangphil_collection";

    @Override
    public Optional<Person> findById(String id) {
        Person person = mongoTemplate.findById(id, Person.class, COLLECTION_NAME);
        return Optional.of(person);
    }

    @Override
    public List<Person> findAll() {
        return mongoTemplate.findAll(Person.class, COLLECTION_NAME);
    }

    @Override
    public <S extends Person> List<S> saveAll(Iterable<S> entities) {
        return null;
    }

    @Override
    public List<Person> findAll(Sort sort) {
        return null;
    }

    @Override
    public <S extends Person> S insert(S entity) {
        return null;
    }

    @Override
    public <S extends Person> List<S> insert(Iterable<S> entities) {
        return null;
    }

    @Override
    public <S extends Person> List<S> findAll(Example<S> example) {
        return null;
    }

    @Override
    public <S extends Person> List<S> findAll(Example<S> example, Sort sort) {
        return null;
    }

    @Override
    public Page<Person> findAll(Pageable pageable) {
        return null;
    }

    @Override
    public <S extends Person> S save(S entity) {
        return null;
    }

    @Override
    public boolean existsById(String s) {
        return false;
    }

    @Override
    public Iterable<Person> findAllById(Iterable<String> strings) {
        return null;
    }

    @Override
    public long count() {
        return 0;
    }

    @Override
    public void deleteById(String s) {

    }

    @Override
    public void delete(Person entity) {

    }

    @Override
    public void deleteAllById(Iterable<? extends String> strings) {

    }

    @Override
    public void deleteAll(Iterable<? extends Person> entities) {

    }

    @Override
    public void deleteAll() {

    }

    @Override
    public <S extends Person> Optional<S> findOne(Example<S> example) {
        return Optional.empty();
    }

    @Override
    public <S extends Person> Page<S> findAll(Example<S> example, Pageable pageable) {
        return null;
    }

    @Override
    public <S extends Person> long count(Example<S> example) {
        return 0;
    }

    @Override
    public <S extends Person> boolean exists(Example<S> example) {
        return false;
    }

    @Override
    public <S extends Person, R> R findBy(Example<S> example, Function<FluentQuery.FetchableFluentQuery<S>, R> queryFunction) {
        return null;
    }
}

重点是前两个函数,findAll和findById。后面的函数本项目中暂不使用。

(3)写一个控制器:

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.Optional;

@RestController
@RequestMapping("/person") //父域
public class PersonController {
    @Autowired
    private PersonRepositoryImpl personRepository;

    public PersonController(PersonRepositoryImpl personRepository) {
        this.personRepository = personRepository;
    }

    @GetMapping("")
    public String getAllPerson() {
        List<Person> persons = personRepository.findAll();
        String str = "";
        for (Person p : persons) {
            str = str + p + "\n";
        }

        return str;
    }

    @GetMapping("/{personId}")
    public String findByPersonId(@PathVariable String personId) {
        Optional<Person> optional = personRepository.findById(personId);
        return optional.get().toString();
    }
}

(4)在application.properties里面定义MongoDB的访问配置:

spring.data.mongodb.host=localhost
spring.data.mongodb.port=27017
spring.data.mongodb.database=zhangphil_db

写好后,运行,在浏览器访问 http://localhost:8080/person

返回结果:

{id='61dea31fe74004760a936564', name='zhangphil', city='Chengdu', age='2021', it=[spring, mongo, mysql, python, android, java]}

在浏览器访问 

http://localhost:8080/person/61dea31fe74004760a936564

返回:

{id='61dea31fe74004760a936564', name='zhangphil', city='Chengdu', age='2021', it=[spring, mongo, mysql, python, android, java]}

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com