Spring Boot 系列 | 第八篇:集成MongoDB
本篇文章主要介绍Spring Boot
如何使用Mongodb
。
添加依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-mongodb</artifactId>
</dependency>
配置
默认情况下,如果Mongodb
没有设置密码的话不需要配置也可以使用,Spring Boot
会默认开启配置的,具体请看MongoProperties.java
文件.
配置如下:
# 无密码的配置
spring.data.mongodb.uri=mongodb://localhost:27017/demo
# 有密码的配置
#spring.data.mongodb.uri=mongodb://name:pass@localhost:27017/dbname
定义一个简单的实体:
@Document(collection = "MongoUser")
public class MongoUser {
@Id
private String id;
private String name;
private Integer age;
public MongoUser(String name, Integer age) {
this.name = name;
this.age = age;
}
@Override
public String toString() {
return "MongoUser{" +
"id='" + id + '\'' +
", name='" + name + '\'' +
", age=" + age +
'}';
}
}
通过一个@ID
注解声明了key
。
也可以通过@Document
指定集合名称
数据操作DAO
的两种方式:
继承MongoRepository
public interface MongoUserRepository extends MongoRepository<MongoUser, String> {
}
写一个接口,继承MongoRepository
,这个几口会默认实现了基本的CURD
操作,也支持自定义的查询,这里先不详解,文章后面再继续讲解。
使用MongoTemplate
@Repository
public class MongoService {
@Resource
MongoTemplate mongoTemplate;
public void save(MongoUser user) {
mongoTemplate.save(user);
}
public List<MongoUser> findAll() {
return mongoTemplate.findAll(MongoUser.class);
}
public void deleteAll() {
mongoTemplate.remove(new Query(), MongoUser.class);
}
}
我这里为了简便省略了接口的声明,实际开发中不可省略。
测试
@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest
public class MongoDbTest {
@Resource
MongoUserRepository userRepository;
@Resource
MongoService mongoService;
@Test
public void testByRepository() {
userRepository.save(new MongoUser("wangjianfeng", 24));
userRepository.save(new MongoUser("wangjianfeng1", 24));
System.out.println("MongoUser found with findAll():");
for (MongoUser customer : userRepository.findAll()) {
System.out.println(customer);
}
userRepository.deleteAll();
}
@Test
public void testByTemplate() {
mongoService.save(new MongoUser("wangjianfeng", 24));
mongoService.save(new MongoUser("wangjianfeng1", 24));
System.out.println("MongoUser found with findAll():");
for (MongoUser customer : userRepository.findAll()) {
System.out.println(customer);
}
mongoService.deleteAll();
}
}
两个测试方法都输出:
MongoUser found with findAll():
MongoUser{id='5a97c09ef5b0fb24699e6076', name='wangjianfeng', age=24}
MongoUser{id='5a97c09ef5b0fb24699e6077', name='wangjianfeng1', age=24}
MongoRepository的拓展
上面说了,继承MongoRepository
这个接口只实现了基本的CURD
操作,如果需要个性化的操作可以按照以下规则定义接口方法:
findBy{Filed}{Condition}
方法传入的参数即Filed
的值,还可以通过传入一个Pageable
进行分页查找
如下:
Page<MongoUser> findByAgeGreaterThan(int age, Pageable pageable);
查找大于age
的数据。
下面列出一些例子
Condition | Method Example | MongoDB 原生查询语句 |
---|---|---|
GreaterThan | findByAgeGreaterThan(int age) | {"age":{"$gt":age}} |
LessThan | findByAgeLessThan(int age) | {"age":{"$lt":age}} |
Between | findByAgeBetween(int from ,int to) | {"age" : {"$gt" : from, "$lt" : to}} |
IsNotNull NotNull | findByAgeNotNull() | {"age" : {"$ne" : null}} |
IsNull, Null | findByAgeNull() | {"age" : null} |
Like | findByNameLike(String name) | {"age" : age} |
(No keyword) | findByName(String name) | {"age" : name} |
Not | findByNameNot(String name) | {"age" : {"$ne" : name}} |
Near (查询地理位置相近的) | findByLocationNear(Point point) | {"location" : {"$near" : [x,y]}} |
Within (在地理位置范围内的) | findByLocationWithin(Circle circle) | {"location" : {"$within" : {"$center" : [ [x, y], distance]}}} |
Within (在地理位置范围内的) | findByLocationWithin(Box box) | {"location" : {"$within" : {"$box" : [ [x1, y1], x2, y2]}}} |
除此之外,还提供mongodb
原生语句查询:
@Query("{'name':{'$regex':?0,'$options':'i'})
public List<Product> findByNameAndAgeRange(String name,int ageFrom,int ageTo);
其中 ?0
是占位符,表示第1个参数。
参考: