MongoDB部署和Springboot整合


MongoDB部署和Springboot整合

目录:

  1. 安装MongoDB
  2. 启动MongoDB
  3. 客户端连接MongoDB
  4. Springboot整合MongoDB

参考/来源:

安装MongoDB

启动MongoDB服务

这里只说MacOS环境下,其他系统类似。

  1. 创建data和log文件夹

    用来存储数据库数据和日志文件

    mkdir data
    mkdir log

    这里可以放在安装包目录下

  2. mongod命令启动MongoDB服务

    mongod常用参数如下

    参数 描述
    –bind_ip 绑定服务IP,若绑定127.0.0.1,则只能本机访问,不指定默认本地所有IP
    –logpath 定MongoDB日志文件,注意是指定文件不是目录
    –logappend 使用追加的方式写日志
    –dbpath 指定数据库路径
    –port 指定服务端口号,默认端口27017
    –serviceName 指定服务名称
    –serviceDisplayName 指定服务名称,有多个mongodb服务时执行。
    –install 指定作为一个Windows服务安装。

    mongod的启动参数,在window环境下和linux环境下并不相同,详见mongod - mongodb启动服务工具

    ./bin/mongod --dbpath data --logpath log/mongodb.log --logappend
  3. 客户端访问MonogDB

    ./bin/mongo

Springboot整合MongoDB

Springboot通过Spring Data方式整合MongoDB,又可以分为MongoRepositoryMongoTemplate两种方法

依赖

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

配置参数

spring:
  data:
    mongodb:
      host: localhost
      port: 27017
      database: test
      #username: admin 这里如果没有对mongodb配置用户名和密码就不设置
      #password: 123456

参数介绍:

  • spring.data.mongodb.host: 指定 MongoDB Server 地址
  • spring.data.mongodb.port: 指定 MongoDB Server 端口
  • spring.data.mongodb.database: 指定使用的数据库
  • spring.data.mongodb.username: MongoDB 用户名
  • spring.data.mongodb.password: MongoDB 密码

MongoRepository方式

数据访问层Repository

package com.pkslow.mongo.dal;

import com.pkslow.mongo.model.User;
import org.springframework.data.mongodb.repository.MongoRepository;
import org.springframework.stereotype.Repository;

@Repository // 注意,我使用Spring Data 方式时,这里没有加过@Repository,很奇怪,也没报错
public interface UserRepository extends MongoRepository<User, String> {
}

调用

import com.pkslow.mongo.dal.UserRepository;
import com.pkslow.mongo.model.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    private final UserRepository userRepository;

    public UserController(UserRepository userRepository) {
        this.userRepository = userRepository;
    }

    @GetMapping("")
    public List<User> getAllUsers() {
        return userRepository.findAll();
    }

    @GetMapping("/{userId}")
    public User getByUserId(@PathVariable String userId) {
        return userRepository.findById(userId).orElse(new User());
    }

    @PostMapping("")
    public User addNewUser(@RequestBody User user) {
        return userRepository.save(user);
    }

    @DeleteMapping("/{userId}")
    public String delete(@PathVariable String userId) {
        User user = new User();
        user.setUserId(userId);
        userRepository.deleteById(userId);
        return "deleted: " + userId;
    }

    @PutMapping("")
    public User update(@RequestBody User user) {
        return userRepository.save(user);
    }
}

Repository的生成规则

方法关键字 示例 等价于SQL
And findByLastnameAndFirstname … where x.lastname = ?1 and x.firstname = ?2
Or findByLastnameOrFirstname … where x.lastname = ?1 or x.firstname = ?2
Is,Equals findByFirstname,findByFirstnameIs,findByFirstnameEquals … where x.firstname = ?1
Between findByStartDateBetween … where x.startDate between ?1 and ?2
LessThan findByAgeLessThan … where x.age < ?1
LessThanEqual findByAgeLessThanEqual … where x.age <= ?1
GreaterThan findByAgeGreaterThan … where x.age > ?1
GreaterThanEqual findByAgeGreaterThanEqual … where x.age >= ?1
After findByStartDateAfter … where x.startDate > ?1
Before findByStartDateBefore … where x.startDate < ?1
IsNull findByAgeIsNull … where x.age is null
IsNotNull,NotNull findByAge(Is)NotNull … where x.age not null
Like findByFirstnameLike … where x.firstname like ?1
NotLike findByFirstnameNotLike … where x.firstname not like ?1
StartingWith findByFirstnameStartingWith … where x.firstname like ?1(参数绑定附加%)
EndingWith findByFirstnameEndingWith … where x.firstname like ?1(参数与预先绑定%)
Containing findByFirstnameContaining … where x.firstname like ?1(参数绑定%)
OrderBy findByAgeOrderByLastnameDesc … where x.age = ?1 order by x.lastname desc
Not findByLastnameNot … where x.lastname <> ?1
In findByAgeIn(Collection ages) … where x.age in ?1
NotIn findByAgeNotIn(Collection ages) … where x.age not in ?1
True findByActiveTrue() … where x.active = true
False findByActiveFalse() … where x.active = false
IgnoreCase findByFirstnameIgnoreCase … where UPPER(x.firstame) = UPPER(?1)

MongoTemplate方式

数据访问层

import com.pkslow.mongo.model.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.stereotype.Repository;
import java.util.List;

@Repository
public class UserDALImpl implements UserDAL {

    @Autowired
    private MongoTemplate template;

    @Override
    public List<User> findAll() {
        return template.findAll(User.class);
    }

    @Override
    public User findById(String userId) {
        return template.findById(userId,User.class);
    }

    @Override
    public User save(User user) {
        return template.save(user);
    }

    @Override
    public void deleteById(String userId) {
        Query query = new Query();
        query.addCriteria(Criteria.where("userId").is(userId));
        template.remove(query, User.class);
    }
}

更多调用

可以参考:https://www.mydlq.club/article/85


文章作者: 小小千千
版权声明: 本博客所有文章除特別声明外,均采用 CC BY 4.0 许可协议。转载请注明来源 小小千千 !
评论
  目录