Springboot 集成mongo 常用的两种方式
Spring Boot 操作 MongoDB 有两种⽐较流⾏的使⽤⽅法:
- 将 MongoTemplate 直接注⼊到 Dao 中使⽤
MongoTemplate 提供了⾮常多的操作 MongoDB ⽅法,它是线程安全的,可以在多线程的情况下使⽤。
MongoTemplate 实现了 MongoOperations 接⼝, 此接⼝定义了众多的操作⽅法如 find、findAndModify、findOne、insert、remove、save、update and updateMulti 等。它转换 domain object 为 DBObject,并提供了 Query、Criteria and Update 等流式 API。
- 继承 MongoRepository,MongoRepository 内置了很多⽅法可直接使⽤。
MongoRepository 继承于 PagingAndSortingRepository,再往上就是 CrudRepository, MongoRepository 和JPA、Elasticsearch 的使⽤⽐较类似,都是 Spring Data 家族的产品,最终使
⽤⽅法也就和 JPA、ElasticSearch 的使⽤⽅式类似,可以根据⽅法名⾃动⽣成 SQL 来查询。
其中第二种方式不加@EnableMongoRepositories注解也可以
一个可以work的demo
1. 添加依赖
<!-- spring data mongodb -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-mongodb</artifactId>
</dependency>
2. Entity
import lombok.Data;
import org.springframework.data.mongodb.core.mapping.Document;
import org.springframework.data.mongodb.core.mapping.Field;
@Data
@Document(collection = "segmentation_user_cohort")
public class SegmentationUserCohort {
/*@Id // not required
private Long id;*/
@Field("user_id")
private Integer userId;
@Field("amplitude_cohort_id")
private String amplitudeCohortId;
@Field("version")
private Integer version;
}
3. MongoRepository
import com.sun.user.segmentation.entity.SegmentationUserCohort;
import org.springframework.data.mongodb.repository.MongoRepository;
import java.util.List;
public interface SegmentationUserCohortRepo extends MongoRepository<SegmentationUserCohort, Long> {
List<SegmentationUserCohort> findSegmentationUserCohortByUserId(Integer userId);
List<SegmentationUserCohort> findSegmentationUserCohortsByAmplitudeCohortId(String amplitudeCohortId);
}
4. application.yml
#
# spring
#
spring:
data:
# mongodb:
# uri: mongodb://localhost:27017/user-segmentation
# username: root
# password: root
# host: localhost
# port: 27017
# database: user-segmentation
mongodb:
uri: mongodb://root:root@localhost:27017
database: user_segmentation
5. 启动类
@SpringBootApplication(exclude = {WebSupportAutoConfiguration.class, SentinelWebAutoConfiguration.class})
// @EnableMongoRepositories(basePackageClasses = SegmentationUserCohort.class)
public class UnitTestApplication {
public static void main(String[] args) {
try {
SpringApplication.run(UnitTestApplication.class, args);
} catch (Exception e) {
System.out.println(e);
}
}
}
6. Test
import com.sun.user.segmentation.entity.SegmentationUserCohort
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.boot.test.autoconfigure.data.mongo.DataMongoTest
import spock.lang.Specification
@DataMongoTest
class SegmentationUserCohortRepoTest extends Specification {
@Autowired
SegmentationUserCohortRepo segmentationUserCohortRepo;
def "get segmentation user cohort by id"() {
given:
def user_id = 1
when:
List<SegmentationUserCohort> segmentationUserCohortList = segmentationUserCohortRepo.findSegmentationUserCohortByUserId(user_id)
then:
segmentationUserCohortList.size() == 1
}
}
参考
[1] Accessing Data with MongoDB: https://spring.io/guides/gs/accessing-data-mongodb/
[2] Spring Boot中使用MongoDB,使用 Repository以及使用MongoTemplate: https://blog.csdn.net/qq_42799615/article/details/113844852
[3] SpringBoot2.x集成MongoDB,使用MongoTemplate操作: https://zhuanlan.zhihu.com/p/98379737
[4] mongodb+Java用法: https://pdai.tech/md/db/nosql-mongo/mongo-x-usage-5.html
[5] Spring Boot集成MongoDB,基于MongoRepository与MongoTemplate操作MongoDB: https://blog.csdn.net/qq_38628046/article/details/119956432
[6] SpringBoot 中使用 MongoDB 基于 MongoRepository增删改查(基础篇): https://blog.csdn.net/weixin_43935907/article/details/86568387
[7] SpringBoot整合MongoDB(一): https://blog.csdn.net/leilei1366615/article/details/104340891
[8] SpringBoot整合MongoDB(阿里云开发社区)(好文章):https://developer.aliyun.com/article/824646
[9] SpringBoot单元测试(一)(掘金)(好文章)(springboot测试jpa,mongo,jdbc,etc.): https://juejin.cn/post/7112071374889959454