Spring Boot 中应用Spring data mongdb
<div class="markdown_views"><h3 id="摘要">摘要<button class="cnblogs-toc-button" title="显示目录导航" aria-expanded="false"></button></h3>
本文主要简单介绍下如何在 Spring Boot 项目中使用 Spring data mongdb. 没有深入探究,仅供入门参考。
文末有代码链接
准备
安装 mongodb
需要连接 mongodb,所以需要提前安装 mongodb. 在本地安装
安装文档见官网 install mongodb
安装完 mongodb 后配置环境变量。创建目录“C:\data\db”作为 mongo 数据存储的默认文件
注意本篇文章代码连接的 mongo3.2.
在 window7 64 bit 上安装 mongo,可以选择 Windows Server 2008 R2 64-bit
例程
配置数据库连接
在 main/resource/ 下添加 application.yml 文件
spring:
data:
mongodb:
host: localhost
port: 27017
database: test
Spring boot 会检测 MongoDb 中是否存在 db test。如果没有会创建
model
创建一个 person document 类。作为 Mongodb 的 document 映射。加上 @Document 注解
@Document(collection="personDocument")
public class PersonDocument {
@Id
String id;
String name;
String description;
}
repository
repository 就是 DAO, 将域类型和它的 ID 类型作为类型参数。Spring Data JPA 在 JPA(Java Persistence Api) 又做了一层封装。因此我们可以看到,只需要编写 repository 接口即可。
@Repository
public interface PersonRepository extends MongoRepository<PersonDocument,String>{
PersonDocument findByName(String name);
}
这些接口会通过 Proxy 来自动实现。所以接口里面的方法名不是随意写。需要遵循一定的规范。像上面的 “findByName”是查询语句,Name 必须是 PersonDocument 中的字段,否则会报错。
And 关键字表示的就是 SQL 中的 and
LessThan 关键词表示的就是 SQL 中的 <
等等,还有许多基本的 SQL 实现
service
service 层和之前的写法没什么不同,调用 repository,实现业务逻辑
@EnableMongoRepositories(basePackages = "com.example.dao.repository")
@Service
public class PersonServiceImpl implements PersonService{
@Autowired
private PersonRepository personRepo;
public PersonDocument getPersonDocumentByName(String name) {
PersonDocument doc = personRepo.findByName(name);
return doc;
}
public PersonDocument create(PersonDocument personDoc) {
personDoc = personRepo.save(personDoc);
return personDoc;
}
}
test
@SpringBootApplication
public class DemoApplication implements CommandLineRunner {
@Autowired
private PersonService personService;
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
@Override
public void run(String... arg0) throws Exception {
PersonDocument doc = new PersonDocument("tom", "student");
personService.create(doc);
PersonDocument doc2 = personService.getPersonDocumentByName("tom");
System.out.println("result:" + doc2.getName());
}
完整代码 github source code
Issues
Q1. 连接 mongodb 正常,数据库中也有 populate 数据。但是使用 spring-data-mongo repository 查询不出数据
A1. 首先试了下 findAll 方法。发现没有查询出数据。最后检查了下 application 配置文件。这个文件没有报错。配置的 Mongo 连接参数也对。要不然也连接不上。虽然文件没有报错。但是有 warning. 参考了标准配置后解决了问题
参考
http://docs.spring.io/spring-data/mongodb/docs/1.2.x/reference/html/mongo.repositories.html
https://github.com/springside/springside4/wiki/Spring-Data-JPA