Spring Boot源码:使用MongoDB MongoTemplate公开REST在几分钟内实现CRUD功能

解道jdon 2021-05-04 12:34:42
spring 源码 mongodb 使用 boot



import com.fasterxml.jackson.annotation.JsonProperty;
import lombok.Getter;
import lombok.Setter;
import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;
public class User {
    private String userId;
    private int rollno;
    private String name;
    private int mobno;
    private Address address;
//Using Lombok for getter and setter


public interface UserService {
    List<User> getAllUsers();
    User getUserById(int userId);
    User addNewUser(User user);
    UpdateResult updateUser(User user);
    User deleteUser(int usrId);


public class ApiController {
    private UserService userService;
// This method Save user in Database
    @PostMapping(value = "/adduser")
    public User addUser(@RequestBody User user) {
        if (user!=null) {
            return userService.addNewUser(user);
        else {
            throw new RuntimeException("Please provide the user detail to create new user");
// This method get user from Database for specific ID
    @RequestMapping(value = "/getuser/{userId}")
    public User getUserById(@PathVariable("userId") String userId) {
        int usrId = 0;
        usrId = Integer.valueOf(userId);
        User user = userService.getUserById(usrId);
        if (user!=null){
            return userService.getUserById(usrId);
            throw new RuntimeException("No user found with userId: " +  userId);
// This method get all user from Database 
    @GetMapping(value = "/getallusers")
    public List<User> getAllUser() {
        return userService.getAllUsers();
// This method update user in Database
    @PutMapping(value = "/updateuser")
    public UpdateResult updateUser(@RequestBody User user) {
        return userService.updateUser(user);
// This method d delete user from Database
    @DeleteMapping(value = "/deleteuser/{userId}")
    public User updateUser(@PathVariable("userId") String userId) {
        int usrId = 0;
        usrId = Integer.valueOf(userId);
        return userService.deleteUser(usrId);


public class UserServiceImpl implements UserService {
    private MongoTemplate mongoTemplate;
    public List<User> getAllUsers() {
        return mongoTemplate.findAll(User.class);
    public User getUserById(int rollno) throws RuntimeException{
        Query query = new Query();
        User user =  mongoTemplate.findOne(query, User.class);
        if (user!=null){
            return user;
        else {
            throw new UserNotFoundException("User not found");
    public User addNewUser(User user) {
        Assert.notNull(user, "Object to save must not be null!");
        return mongoTemplate.save(user);
    public UpdateResult updateUser(User user) {
        Query query = new Query();
        Document doc = new Document(); // org.bson.Document
        mongoTemplate.getConverter().write(user, doc);
        return mongoTemplate.upsert(query, Update.fromDocument(doc), User.class);
    public User deleteUser(int usrId) {
        Query query = new Query();
        return mongoTemplate.findAndRemove(query, User.class);



  1. Spring 3中异步方法调用
  2. AOP相关讨论
  3. jf能支持的表现层目前只有struts 1.x么?
  4. 在j2ee中实现一般java对象数据库的方法。
  5. FTP connecting windows and Linux
  6. Decorator design pattern - gene zeiniss
  7. Asynchronous method call in spring 3
  8. Discussion on AOP
  9. Is struts 1. X the only presentation layer supported by JF?
  10. The method of realizing general Java object database in J2EE.
  11. PDF转HTML工具——用springboot包装pdf2htmlEX命令行工具
  12. Pdf to HTML tool -- Wrapping pdf2htmlex command line tool with springboot
  13. MySQL 的 in 查询不走索引?我拿什么拯救你!
  14. MySQL in query does not go index? What can I do to save you!
  15. PDF转HTML工具——用springboot包装pdf2htmlEX命令行工具
  16. Pdf to HTML tool -- Wrapping pdf2htmlex command line tool with springboot
  17. Java小白入门必学!最全数据类型和运算符笔记,附实例
  18. Java Xiaobai introduction must learn! Notes on the most complete data types and operators, with examples
  19. Spring MVC请求与响应
  20. Spring MVC request and response
  21. Java 11已经不再完全免费,不要陷入Oracle的Java 11陷阱
  22. Vue.js比jQuery更容易学习
  23. 启动/删除Docker容器时出现问题 - 如何修复
  24. eclipse run on server时出现了错误信息.求急!!
  25. 请教高手一个关于lunce的问题:java.io.IOException: Cannot rename ...\segments.new
  26. Java 11 is no longer completely free. Don't fall into the Java 11 trap of Oracle
  27. Vue. JS is easier to learn than jQuery
  28. Problem starting / deleting docker container - how to fix it
  29. There is an error message in eclipse run on server!!
  30. Ask a question about lunce: java.io.ioexception: cannot rename... \ segments.new
  31. 从零搭建Spring Boot脚手架(2):集成mybatis
  32. 从零搭建Spring Boot脚手架(4):手写Mybatis通用Mapper
  33. 只知道java反射,宁知道内省吗?
  34. Build spring boot scaffold from scratch (2): integrate mybatis
  35. Build spring boot scaffold from scratch (4): handwritten mybatis general mapper
  36. Do you prefer introspection to reflection?
  37. ASP调用SDK微信分享好友、朋友圈
  38. ASP calls SDK wechat to share friends and circle of friends
  39. BAT 必问的 MySQL 面试题你都会吗?
  40. Do you know all the MySQL interview questions that bat must ask?
  41. ASP调用SDK微信分享好友、朋友圈
  42. ASP calls SDK wechat to share friends and circle of friends
  43. SpringCloud(六)Bus消息总线
  44. 详解JavaScript中的正则表达式
  45. Springcloud (6) bus message bus
  46. Explain regular expressions in JavaScript
  47. Java 响应式关系数据库连接了解一下
  48. Java14它真的来了, 真是尾气都吃不到了
  49. 视频:使用Docker搭建RabbitMQ环境
  50. Java responsive relational database connection
  51. Java14 it's really coming. I can't eat the exhaust
  52. Video: building rabbitmq environment with docker
  53. SpringCloud(六)Bus消息总线
  54. 详解JavaScript中的正则表达式
  55. Springcloud (6) bus message bus
  56. Explain regular expressions in JavaScript
  57. Docker实战:用docker-compose搭建Laravel开发环境
  58. Docker: building laravel development environment with docker compose
  59. 求助,JAVA如何获取系统当前所有进程
  60. 有人用过JMeter或用HttpUnit写过测试吗????