(1)依赖
compile('org.springframework.boot:spring-boot-starter-data-mongodb')
(2)application.properties配置文件
spring.data.mongodb.host=127.0.0.1
spring.data.mongodb.port=27017
spring.data.mongodb.database=test
(3)User类
@Data
public class User {Integer id;String name;Integer age;Date birth;public User(Integer id, String name, Integer age, Date birth) {super();this.id = id;this.name = name;this.age = age;this.birth = birth;}}
(4)UserService类
@Service
public class UserService {@AutowiredMongoTemplate mongoTemplate;public void insert(User user) {mongoTemplate.insert(user);}public long update(String name, User user) {Query query = new Query();Criteria c = new Criteria();c.and("name").is(name);query.addCriteria(c);Update update= new Update();update.set("age", user.getAge());update.set("birth", user.getBirth());WriteResult result = mongoTemplate.upsert(query, update, User.class);return result.getN();}public long remove(String name) {Query query = new Query();Criteria c = new Criteria();c.and("name").is(name);query.addCriteria(c);WriteResult result = mongoTemplate.remove(query, User.class);return result.getN();}public User findOne(String name, Integer age) {Query query = new Query();Criteria c = new Criteria();c.and("name").is(name);c.and("age").gte(age);query.addCriteria(c);return mongoTemplate.findOne(query, User.class);}public List<User> find(Integer age) {Query query = new Query();Criteria c = new Criteria();c.and("age").gt(age);query.addCriteria(c);return mongoTemplate.find(query, User.class);}public long count(Integer age) {Query query = new Query();Criteria c = new Criteria();c.and("age").gte(age);query.addCriteria(c);return mongoTemplate.count(query, User.class);}}
(5)测试和测试结果
User user1 = new User(1, "tom", 1, new Date());
User user2 = new User(2, "jerry", 2, new Date());
User user3 = new User(3, "diana", 3, new Date());
userService.insert(user1);
userService.insert(user2);
userService.insert(user3);
User user = userService.findOne("tom", 1);
log.info("user:{}", user);
List<User> list = userService.find(1);
log.info("list:{}", list);
long count = userService.count(1);
log.info("count:{}", count);
User tom = new User(1, "tom", 5, new Date());
long n1 = userService.update("tom", tom);
log.info("n1:{}", n1);
long n2 = userService.remove("tom");
log.info("n2:{}", n2);
2024-01-26 16:21:15 [http-nio-8080-exec-2] INFO cn.hwd.controller.TestController - user:User(id=1, name=tom, age=1, birth=Fri Jan 26 16:21:15 CST 2024)
2024-01-26 16:21:15 [http-nio-8080-exec-2] INFO cn.hwd.controller.TestController - list:[User(id=2, name=jerry, age=2, birth=Fri Jan 26 16:21:15 CST 2024), User(id=3, name=diana, age=3, birth=Fri Jan 26 16:21:15 CST 2024)]
2024-01-26 16:21:15 [http-nio-8080-exec-2] INFO cn.hwd.controller.TestController - count:3
2024-01-26 16:21:15 [http-nio-8080-exec-2] INFO cn.hwd.controller.TestController - n1:1
2024-01-26 16:21:15 [http-nio-8080-exec-2] INFO cn.hwd.controller.TestController - n2:1