Home > AI > Backend > SpringBoot >

mongodb mannual test

User.java

@Getter
@Setter
@ToString
public class User {
    public int id;
    public String firstName;
    public String lastName;
}

UserDao.java

@Component
public class UserDao {
    @Autowired
    private MongoTemplate mongoTemplate;


    public void save(User user) {
        System.out.println("Save user" + user.toString());
        mongoTemplate.save(user);
    }

    public User findUserByFirstName(String firstName) {
        System.out.println("Find user by firstname" + firstName);
        Query query = new Query(Criteria.where("firstName").is(firstName));
        User user = mongoTemplate.findOne(query, User.class);
        return user;
    }


    public void updateUser(User user) {
        System.out.println("Update user" + user.toString());
        Query query = new Query(Criteria.where("id").is(user.getId()));
        Update update = new Update().set("firstName", user.getFirstName())
                .set("lastName", user.getLastName());
        mongoTemplate.updateFirst(query, update, User.class);
    }

    public void deleteUserById(int id) {
        System.out.println("Delete user" + Integer.toString(id));
        Query query = new Query(Criteria.where("id").is(id));
        mongoTemplate.remove(query, User.class);
    }
}

UserAPI.java

@RestController
public class UserAPI {

    @Autowired
    private UserDao userDao;


    @GetMapping(value = "/test1")
    public void saveTest() throws Exception {
        User user = new User();
        user.setId(11);
        user.setFirstName("Limin");
        user.setLastName("Deng");
        userDao.save(user);
    }

    @GetMapping(value = "/test2")
    public User findUserByFirstName() {
        User user = userDao.findUserByFirstName("Limin");
        return user;
    }

    @GetMapping(value = "/test3")
    public void update() {
        User user = new User();
        user.setId(11);
        user.setFirstName("Mary");
        user.setLastName("Good");
        userDao.updateUser(user);
    }

    @GetMapping(value = "/test4")
    public void deleteUserById() {
        userDao.deleteUserById(11);
    }


}

Leave a Reply