( 十三 )、 SpringBoot 整合 MongoDB

( 十三 )、 SpringBoot 整合 MongoDB

 

 

 

官网: https://docs.spring.io/spring-data/mongodb/docs/3.2.5/reference/html/#mongodb-getting-started

 

1、Maven 依赖

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

 

2、Yml

spring:
  #mongodb配置
  data:
   mongodb:
#    uri: mongodb://admin:admin@127.0.0.1:27017/admin
    uri: mongodb://127.0.0.1:27017/dw

 

方式一:MongoRepository

 1、User

@Data
public class User {
    @Id
    private String userId;
    private String name;
    private Integer age;
    private Date createTime = new Date();
}

 2、IUserRepository

/**
 * @Author dw
 * @ClassName UserRepository
 * @Description 方式一 : 继承 MongoRepository<实体类, 主键ID>
 * @Date 2021/10/25 10:12
 * @Version 1.0
 */
@Repository
public interface IUserRepository extends MongoRepository<User, String> {
}

 3、controller

/**
 * @Author dw
 * @ClassName UserController
 * @Description  方式一 : MongoRepository
 * @Date 2021/10/25 10:16
 * @Version 1.0
 */
@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    private IUserRepository userRepository;


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

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

    @PostMapping("addNewUser")
    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("update")
    public User update(@RequestBody User user) {
        return userRepository.save(user);
    }
}

 

方式二: MongoTemplate
/**
 * @Author dw
 * @ClassName UserTemplateController
 * @Description 方式二: MongoTemplate
 * @Date 2021/10/25 11:28
 * @Version 1.0
 */
@RestController
@RequestMapping("/user")
public class UserTemplateController {

    @Autowired
    private MongoTemplate template;

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

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

    @RequestMapping("/save")
    public User save(User user) {
        return template.save(user);
    }

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

 

posted @ 2021-10-25 15:26  邓维-java  阅读(136)  评论(0编辑  收藏  举报