- 准备集成环境,添加依赖
-
<parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.1.3.RELEASE</version> </parent> <properties> <java.version>1.8</java.version> </properties> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> </dependency> <!--spring boot data mongodb--> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-mongodb</artifactId> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build>
-
- 配置连接参数(application.properties)
-
# application.properties # 配置数据库连接 #格式: mongodb://账号:密码@ip:端口/数据库?认证数据库 spring.data.mongodb.uri=mongodb://root:admin@localhost/mongotest?authSource=admin # 配置MongoTemplate的执行日志 logging.level.org.springframework.data.mongodb.core=debug
-
- domain
- 代码说明
@AllArgsConstructor @NoArgsConstructor @Setter@Getter@ToString @Document("users") //设置文档所在的集合 public class User { @Id //文档的id使用ObjectId类型来封装,并且贴上@Id注解 private ObjectId _id; private Long id; private String name; private Integer age; }
- 代码说明
-
- MongoDBRePository接口
-
/** * 自定义一个接口继承MongoRepository, * 泛型1:domain类型 * 泛型2:文档主键类型 * 贴上@Repository注解,底层会创建出动态代理对象,交给Spring管理 */ @Repository public interface UserMongoRepository extends MongoRepository<User, ObjectId> { // 使用Spring Data命名规范做高级查询 List<User> findByName(String name); }
关于自定义方法的JPA规范
4. 实例代码:
@Autowired private UserMongoRepository repository; // 插入/更新一个文档 @Test public void testSaveOrUpdate() throws Exception { User user = new User(null, 5L, "bunny", 20); // 主键为null则新增,不为null则更新 repository.save(user); } // 删除一个文档 @Test public void testDelete() throws Exception { repository.deleteById(new ObjectId("xxx")); } // 查询一个文档 @Test public void testGet() throws Exception { Optional<User> optional = repository.findById(new ObjectId("xxx")); optional.ifPresent(System.err::println); } // 查询所有文档 @Test public void testList() throws Exception { // 查询所有文档 List<User> list = repository.findAll(); list.forEach(System.err::println); }
5.MongoDBTemplate