【SpringBoot】springboot整合mongoDB
目录
1.配置
创建好springboot工程后
引入mongoDB依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-mongodb</artifactId>
</dependency>
在application.properties中配置
MongoDB的连接信息
格式如下:
spring.data.mongodb.uri=mongodb://user:password@localhost:27017/mydatabase
application.yml格式如下
spring:
data:
mongodb:
uri: mongodb://username:password@localhost:27017/myDatabase
2.使用
创建实体类
@Document(collection = "users")
public class User {
@Id
private String id;
private String name;
private int age;
public User(String id, String name, int age) {
this.id = id;
this.name = name;
this.age = age;
}
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 int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
@Document 注解用于标注实体类,表示一个实体类映射为MongoDB 中的一个文档
@Id 注解用于标注实体类中的主键
创建MongoDB仓库接口
为每个实体创建一个仓库接口,并使用@Repository
注解标记接口
package com.example.demo.repository;
import com.example.demo.po.User;
import org.springframework.data.mongodb.repository.MongoRepository;
import org.springframework.stereotype.Repository;
@Repository
public interface UserRepository extends MongoRepository<User,String> {
}
创建一个控制器
例如
package com.example.demo.controller;
import com.example.demo.po.User;
import com.example.demo.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.List;
import java.util.Optional;
@RestController
@RequestMapping("/users")
public class UserController {
@Autowired
private UserRepository userRepository;
@GetMapping
public List<User> getAllUsers() {
return userRepository.findAll();
}
@GetMapping("/{id}")
public Optional<User> getUserById(@PathVariable String id) {
return userRepository.findById(id);
}
@PostMapping
public User createUser(@RequestBody User user) {
return userRepository.save(user);
}
@DeleteMapping("/{id}")
public void deleteUser(@PathVariable String id) {
userRepository.deleteById(id);
}
}
然后编写相关的服务
类似于mysql