Spring Boot Mongo
spring-boot-starter-data-mongodb
实体类上必须标注:@Document
主键: @Id
主要有两种方式:
Repository
@EnableMongoRepositories
MongoRepository<T, Id>
PagingAndSortingRepository<T, Id>
CrudRepository<T, Id>
MongoTemplate
save/remove/Query/Criteria/Update
主要对应Mongo中的查询器,修改器
-
配置pom.xml
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-mongodb</artifactId> </dependency>
-
编写document
@Document @Data @Builder public class User { @Id private String id; private String username; private String password; private Date createTime; private Date updateTime; }
-
编写repository
@Repository public interface UserDao extends MongoRepository<User, String> { }
-
编写yaml配置文件
spring.data.mongodb.uri: mongodb://shawn:shawn@192.168.1.105:27017/spring-boot-demo
-
编写启动类
@SpringBootApplication @Slf4j @EnableMongoRepositories public class MongoApplication implements ApplicationRunner { @Autowired private UserDao userDao; @Autowired private MongoTemplate mongoTemplate; public static void main(String[] args) { SpringApplication.run(MongoApplication.class, args); } @Override public void run(ApplicationArguments args) throws Exception { User user = User.builder() .id("1") .username("shawn") .password("shawn") .createTime(new Date()) .updateTime(new Date()) .build(); userDao.insert(user); log.info("user {}", user); Optional<User> optional = userDao.findById("1"); log.info("find by id user {}", optional.get()); List<User> list = userDao.findAll(); list.forEach(e -> log.info("findAll User: {}", e)); User condition = User.builder().username("shawn").build(); List<User> userList = userDao.findAll(Example.of(condition)); userList.forEach(e -> log.info("findAll User by Example: {}", e)); Thread.sleep(1000); // 为了看更新时间 user.setPassword("123456"); user.setUpdateTime(new Date()); userDao.save(user); log.info("find by id user {}", userDao.findById("1").get()); userDao.deleteById("1"); userDao.findById("1").ifPresent(u -> log.info("find by id user {}", u)); User user2 = User.builder() .id("2") .username("jack") .password("jack") .createTime(new Date()) .updateTime(new Date()) .build(); mongoTemplate.save(user2); log.info("User2 {}", user2); List<User> user2List = mongoTemplate.find(Query.query(Criteria.where("username").is("jack")), User.class); user2List.forEach(c -> log.info("User2 {}", c)); Thread.sleep(1000); // 为了看更新时间 UpdateResult result = mongoTemplate.updateFirst( Query.query(Criteria.where("username").is("jack")), new Update().set("password", "jack12346").currentDate("updateTime"), User.class); log.info("Update Result: {}", result.getModifiedCount()); User updateOne = mongoTemplate.findById(user2.getId(), User.class); log.info("Update Result: {}", updateOne); mongoTemplate.remove(updateOne); log.info("Update Result: {}", mongoTemplate.findById(user2.getId(), User.class)); } }
网友评论