springboot整合mongodb简单入门

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

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

        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>
spring:
  data:
    mongodb:
      database: rayc
      host: 127.0.0.1
      port: 27017
server:
  port: 8087
entity
@Data
//表名映射
@Document(collection = "rayc")
public class Student {
    @Id
    private String id;
    //字段映射
//    @Field(value = "student_age")
//    private Integer age;
    @Field(value = "name")
    private String name;
}
repository
@Repository
public interface StudentRepository extends MongoRepository<Student,String> {
}
controller
@RestController
public class StudentHandler {

    @Autowired
    private StudentRepository studentRepository;

    @GetMapping("/findAll")
    public List<Student> findAll(){
        return studentRepository.findAll();
    }

    @GetMapping("/findById/{id}")
    public Student findById(@PathVariable("id") String id){
        return studentRepository.findById(id).get();
    }

    @PostMapping("/save")
    public Student save(@RequestBody Student student){
        return studentRepository.save(student);
    }

    @PostMapping("/update")
    public Student update(@RequestBody Student student){
        return studentRepository.save(student);
    }

    @DeleteMapping("/deleteById/{id}")
    public void deleteById(@PathVariable("id") String id){
         studentRepository.deleteById(id);
    }
}
@SpringBootApplication
public class Application {
    public static void main(String[] args) {
        SpringApplication.run(Application.class,args);
    }
}

安装mongdb
新建文件夹
存放
mongo.bat启动文件
内容: mongod.exe --dbpath=D:\environment\mongoDB\mongoDBdata
mongoDBClient.bat客户端文件
内容:mongo.exe 127.0.0.1:27017/admin

启动mongo.bat 然后启动mongoDBClient.bat操作
查看数据库 show dbs
use rayc
db.rayc.find()
在这里插入图片描述
BSON格式数据

postman测试

save
在这里插入图片描述
delete
在这里插入图片描述

update
在这里插入图片描述
findAll
在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值