您的位置:首页 > 编程语言 > Java开发

Spring Boot 中应用Spring data mongdb

2016-09-10 12:48 405 查看

摘要

本文主要简单介绍下如何在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

http://docs.spring.io/spring-data/mongodb/docs/1.4.0.RELEASE/reference/html/mongo.core.html#mongodb-getting-started

https://github.com/springside/springside4/wiki/Spring-Data-JPA
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: