SpringBoot之MongoDB的支持
来源:互联网 发布:布尔玛和孙悟空 知乎 编辑:程序博客网 时间:2024/06/05 22:48
一、简介
MongoDB是一个基于文档(Document)的存储型的数据库,使用面向对象的思想,每一条数据记录都是文档的对象。
是一个介于关系数据库和非关系数据库之间的产品,是非关系数据库当中功能最丰富,最像关系数据库的。他支持的数据结构非常松散,是类似json的bson格式,因此可以存储比较复杂的数据类型。Mongo最大的特点是他支持的查询语言非常强大,其语法有点类似于面向对象的查询语言,几乎可以实现类似关系数据库单表查询的绝大部分功能,而且还支持对数据建立索引。
安装方法:MongoDB的安装(windows+centos)
二、Spring的支持
Spring对MongoDB的支持主要是通过Spring DataMongoDB来实现的,Spring Data MongoDB为我们提供了如下功能。
(1)Object/Document映射注解支持
JPA提供了一套Object/Relation映射的注解(@Entity、@Id),而Spring Data MongoDB也提供了下图所示的注解。
(2)MongoTemplate
像JdbcTemplate一样,Spring Data MongoDB也为我们提供了一个MongoTemplate,ongoTemplate为我们提供了数据访问的方法。我们还需要为MongoClient以及MongoDbFactory来配置数据库连接属性,例如:
@Beanpublic MongoClient client() throws UnknownHostException { MongoClient client = new MongoClient(new ServerAddress("127.0.0.1", 27017)); return client;}@Beanpublic MongoDbFactory mongoDbFactory() throws Exception { String database = new MongoClientURI("mongodb://localhost/test").getDatabase(); return new SimpleMongoDbFactory(client() , database);}@Beanpublic MongoTemplate mongoTemplate(MongoDbFactory mongoDbFactory) throws UnknownHostException { return new MongoTemplate(mongoDbFactory);}
(3)Repository的支持
类似于Spring Data JPA,Spring Data MongoDB也提供了Repository的支持,使用方式和Spring Data JPA一致,定义如下:
public interface PersonRepository extends MongoRepository<Person, String> {}
类似于Spring Data JPA的开启支持方式,MongoDB的Repository的支持开启需在配置类上注解@EnableMongoRepositories,例如:
@Configuration@EnableMongoRepositoriespublic class AppConfig {}
三、SpringBoot的支持
Spring Boot对MongoDB的支持,分别位于org.springframework.boot.autoconfigure.mongo:
主要配置数据库连接、MongoTemplate。我们可以使用以“spring.data.mongodb”为前缀的属性来配置MongoDB相关的信息。Spring Boot为我们提供了一些默认属性,如默认MongoDB的端口为27017、默认服务器为localhost、默认数据库为test。Spring Boot的主要配置如下:
SpringBoot Properties常用应用属性配置列表
# MONGODB (MongoProperties)spring.data.mongodb.authentication-database= # Authentication database name.spring.data.mongodb.database=test # Database name.spring.data.mongodb.field-naming-strategy= # Fully qualified name of the FieldNamingStrategy to use.spring.data.mongodb.grid-fs-database= # GridFS database name.spring.data.mongodb.host=localhost # Mongo server host. Cannot be set with uri.spring.data.mongodb.password= # Login password of the mongo server. Cannot be set with uri.spring.data.mongodb.port=27017 # Mongo server port. Cannot be set with uri.spring.data.mongodb.repositories.enabled=true # Enable Mongo repositories.spring.data.mongodb.uri=mongodb://localhost/test # Mongo database URI. Cannot be set with host, port and credentials.spring.data.mongodb.username= # Login user of the mongo server. Cannot be set with uri.
为我们开启了对Repository的支持,即自动为我们配置了@EnableMongoRepositories。所以我们在Spring Boot下使用MongoDB只需引入spring-boot-starter-data-mongodb依赖即可,无须任何配置。
四、实战
1.安装:安装方法:MongoDB的安装(windows+centos)
2.启动:(本例是在win7上)
3.测试链接:(工具:RoBo 3T)
4.pom.xml
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-jpa</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-mongodb</artifactId> </dependency>
5.MongoInfo
@Document //@Document注解映射领域模型和MongoDB的文档。public class MongoInfo { @Id //2 @Id注解表明这个属性为文档的Id。 private String id; private String name; private Integer age; @Field("locs")//3 @Field注解此属性在文档中的名称为locs,locations属性将以数组形式存在当前数据记录中。 private Collection<Location> locations = new LinkedHashSet<Location>(); public MongoInfo(String name, Integer age) { super(); this.name = name; this.age = age; } //省略get、set}
6.子类Location
public class Location { private String place; private String year; public Location(String place, String year) { super(); this.place = place; this.year = year; } //省略get、set}
7.数据访问MongoInfoRepository
public interface MongoInfoRepository extends MongoRepository<MongoInfo, String> { MongoInfo findByName(String name); //支持方法名查询。 @Query("{'age': ?0}") //支持@Query查询,查询参数构造JSON字符串即可 List<MongoInfo> withQueryFindByAge(Integer age);}
8.控制器MongoInfoController
@RestController@RequestMapping("/mongo")public class MongoInfoController { @Autowired MongoInfoRepository mongoInfoRepository; @RequestMapping("/save") //测试保存数据。 public MongoInfo save(){ MongoInfo mongoInfo = new MongoInfo("aaa", 16); Collection<Location> locations = new LinkedHashSet<Location>(); Location loc1 = new Location("云南", "2009"); Location loc2 = new Location("贵州", "2010"); Location loc3 = new Location("广西", "2011"); Location loc4 = new Location("桂林", "2012"); Location loc5 = new Location("柳州", "2013"); locations.add(loc1); locations.add(loc2); locations.add(loc3); locations.add(loc4); locations.add(loc5); mongoInfo.setLocations(locations); return mongoInfoRepository.save(mongoInfo); } @RequestMapping("/q1") //2测试方法名查询。 public MongoInfo q1(String name){ return mongoInfoRepository.findByName(name); } @RequestMapping("/q2") //3测试@Query查询。 public List<MongoInfo> q2(Integer age){ return mongoInfoRepository.withQueryFindByAge(age); }}
9运行
(1)保存数据到mongodb,运行http://localhost:5000/mongo/save
通过工具查看数据信息:
(2)测试方法名查询,http://localhost:5000/mongo/q1?name=aaa
(3)测试@Query查询http://localhost:5000/mongo/q2?age=16
关于SpringBoot使用mongodb就实现了。
参考资料《JavaEE开发的颠覆者 Spring Boot》