Spring Boot 系列 | 第八篇:集成MongoDB

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的数据。

下面列出一些例子

ConditionMethod ExampleMongoDB原生查询语句
GreaterThanfindByAgeGreaterThan(int age){"age":{"$gt":age}}
LessThanfindByAgeLessThan(int age){"age":{"$lt":age}}
BetweenfindByAgeBetween(int from ,int to){"age" : {"$gt" : from, "$lt" : to}}
IsNotNull NotNullfindByAgeNotNull(){"age" : {"$ne" : null}}
IsNull, NullfindByAgeNull(){"age" : null}
LikefindByNameLike(String name){"age" : age}
(No keyword)findByName(String name){"age" : name}
NotfindByNameNot(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个参数。

参考:

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值