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

20-05-16 banq

源码点击标题进入。

业务失血模型User代码:

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;

@Getter
@Setter
@Document
public class User {

    @Id
    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);
}

REST控制器:

@RestController
public class ApiController {

    @Autowired
    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);
        }
        else
            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);

    }
}

服务实现:

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private MongoTemplate mongoTemplate;

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

    @Override
    public User getUserById(int rollno) throws RuntimeException{
        Query query = new Query();
        query.addCriteria(Criteria.where("rollno").is(rollno));
        User user =  mongoTemplate.findOne(query, User.class);
        if (user!=null){
            return user;
        }
        else {
            throw new UserNotFoundException("User not found");
        }
    }

    @Override
    public User addNewUser(User user) {
        Assert.notNull(user, "Object to save must not be null!");

        return mongoTemplate.save(user);

    }

    @Override
    public UpdateResult updateUser(User user) {
        Query query = new Query();
        query.addCriteria(Criteria.where("rollno").is(user.getRollno()));
        Document doc = new Document(); // org.bson.Document
        mongoTemplate.getConverter().write(user, doc);
        return mongoTemplate.upsert(query, Update.fromDocument(doc), User.class);
    }

    @Override
    public User deleteUser(int usrId) {
        Query query = new Query();
        query.addCriteria(Criteria.where("rollno").is(usrId));
        return mongoTemplate.findAndRemove(query, User.class);

    }

}

 

              

猜你喜欢