MongoDB简介
MongoDB是一个基于分布式文件存储的数据库,它是一个介于关系数据库和非关系数据库之间的产品,其主要目标是在键/值存储方式(提供了高性能和高度伸缩性)和传统的RDBMS系统(具有丰富的功能)之间架起一座桥梁,它集两者的优势于一身。
传统的关系数据库一般由数据库(database)、表(table)、记录(record)三个层次概念组成,MongoDB是由数据库(database)、集合(collection)、文档对象(document)三个层次组成。
MongoDB中的一条记录就是一个文档,是一个数据结构,由字段和值对组成。MongoDB文档与JSON对象类似。字段的值有可能包括其它文档、数组以及文档数组。
MongoDB的适合对大量或者无固定格式的数据进行存储,比如:日志、缓存等。对事物支持较弱,不适用复杂的多文档(多表)的级联查询。
MongoDB的CRUD
- 添加pom.xml依赖
Spring Boot中可以通过在pom.xml中加入spring-boot-starter-data-mongodb引入对mongodb的访问支持依赖。
1. <dependency> 2. <groupId>org.springframework.boot</groupId> 3. <artifactId>spring-boot-starter-data-mongodb</artifactId> 4. </dependency> • 创建Entity对象 5. package com.gemantic.entity; 6. 7. import java.io.Serializable; 8. 9. 10. public class UserEntity implements Serializable { 11. 12. private static final long serialVersionUID = -3258839839160856613L; 13. private Long id; 14. private String userName; 15. private String passWord; 16. 17. 18. // 省略getter和setter 19. } • CRUD 20. package com.gemantic.dao.impl; 21. 22. import com.mongodb.WriteResult; 23. import com.gemantic.entity.UserEntity; 24. import org.springframework.beans.factory.annotation.Autowired; 25. import org.springframework.boot.autoconfigure.security.SecurityProperties; 26. import org.springframework.data.mongodb.core.MongoTemplate; 27. import org.springframework.data.mongodb.core.query.Criteria; 28. import org.springframework.data.mongodb.core.query.Query; 29. import org.springframework.data.mongodb.core.query.Update; 30. import org.springframework.stereotype.Service; 31. 32. 33. @Service 34. public class UserDaoImpl implements UserDao { 35. 36. @Autowired 37. private MongoTemplate mongoTemplate; 38. 39. /** 40. * 创建对象 41. * @param user 42. */ 43. @Override 44. public void saveUser(UserEntity user) { 45. mongoTemplate.save(user); 46. } 47. 48. /** 49. * 根据用户名查询对象 50. * @param userName 51. * @return 52. */ 53. @Override 54. public UserEntity findUserByUserName(String userName) { 55. Query query = new Query(Criteria.where("userName").is(userName)); 56. UserEntity user = mongoTemplate.findOne(query , UserEntity.class); 57. return user; 58. } 59. 60. /** 61. * 更新对象 62. * @param user 63. */ 64. @Override 65. public int updateUser(UserEntity user) { 66. Query query = new Query(Criteria.where("id").is(user.getId())); 67. Update update = new Update().set("userName", user.getUserName()).set("passWord", user.getPassWord()); 68. //更新查询返回结果集的第一条 69. WriteResult result = mongoTemplate.updateFirst(query, update, UserEntity.class); 70. //更新查询返回结果集的所有 71. // mongoTemplate.updateMulti(query, update, UserEntity.class); 72. if(result != null) { 73. return result.getN(); 74. } else { 75. return 0; 76. } 77. } 78. 79. /** 80. * 删除对象 81. * @param id 82. */ 83. @Override 84. public void deleteUserById(Long id) { 85. Query query = new Query(Criteria.where("id").is(id)); 86. mongoTemplate.remove(query, UserEntity.class); 87. } 88. }
多数据源MongoDB的使用
- 配置多数据源,这里配置两个数据源
application.yml
- 注意事项
1. mongodb: 2. primary: 3. host: 192.168.1.50 4. port: 27017 5. database: test 6. secondary: 7. host: 192.168.1.60 8. port: 27017 9. database: test1 • 封装读取以mongodb开头的两个配置文件 10. package com.gemantic.config; 11. 12. import lombok.Data; 13. import org.springframework.boot.autoconfigure.mongo.MongoProperties; 14. import org.springframework.boot.context.properties.ConfigurationProperties; 15. 16. 17. @Data 18. @ConfigurationProperties(prefix = "mongodb") 19. public class MultipleMongoProperties { 20. 21. private MongoProperties primary = new MongoProperties(); 22. private MongoProperties secondary = new MongoProperties(); 23. } • 配置不同包路径下使用不同的数据源 PrimaryMongoConfig 1. package com.gemantic.config; 2. 3. import org.springframework.context.annotation.Configuration; 4. import org.springframework.data.mongodb.repository.config.EnableMongoRepositories; 5. 6. 7. @Configuration 8. @EnableMongoRepositories(basePackages = "com.gemantic.model.primary", 9. mongoTemplateRef = PrimaryMongoConfig.MONGO_TEMPLATE) 10. public class PrimaryMongoConfig { 11. 12. protected static final String MONGO_TEMPLATE = "primaryMongoTemplate"; 13. } SecondaryMongoConfig 1. package com.gemantic.config; 2. 3. import org.springframework.context.annotation.Configuration; 4. import org.springframework.data.mongodb.repository.config.EnableMongoRepositories; 5. 6. 7. @Configuration 8. @EnableMongoRepositories(basePackages = "com.gemantic.model.secondary", 9. mongoTemplateRef = SecondaryMongoConfig.MONGO_TEMPLATE) 10. public class SecondaryMongoConfig { 11. 12. protected static final String MONGO_TEMPLATE = "secondaryMongoTemplate"; 13. } • 读取对应的配置信息并且构造对应的MongoTemplate,以下代码对两个库的配置信息已经完成。 14. package com.gemantic.config; 15. 16. import com.mongodb.MongoClient; 17. import com.gemantic.config.MultipleMongoProperties; 18. import org.springframework.beans.factory.annotation.Autowired; 19. import org.springframework.beans.factory.annotation.Qualifier; 20. import org.springframework.boot.autoconfigure.mongo.MongoProperties; 21. import org.springframework.context.annotation.Bean; 22. import org.springframework.context.annotation.Configuration; 23. import org.springframework.context.annotation.Primary; 24. import org.springframework.data.mongodb.MongoDbFactory; 25. import org.springframework.data.mongodb.core.MongoTemplate; 26. import org.springframework.data.mongodb.core.SimpleMongoDbFactory; 27. 28. 29. @Configuration 30. public class MultipleMongoConfig { 31. 32. @Autowired 33. private MultipleMongoProperties mongoProperties; 34. 35. @Primary 36. @Bean(name = PrimaryMongoConfig.MONGO_TEMPLATE) 37. public MongoTemplate primaryMongoTemplate() throws Exception { 38. return new MongoTemplate(primaryFactory(this.mongoProperties.getPrimary())); 39. } 40. 41. @Bean 42. @Qualifier(SecondaryMongoConfig.MONGO_TEMPLATE) 43. public MongoTemplate secondaryMongoTemplate() throws Exception { 44. return new MongoTemplate(secondaryFactory(this.mongoProperties.getSecondary())); 45. } 46. 47. @Bean 48. @Primary 49. public MongoDbFactory primaryFactory(MongoProperties mongo) throws Exception { 50. return new SimpleMongoDbFactory(new MongoClient(mongo.getHost(), mongo.getPort()), 51. mongo.getDatabase()); 52. } 53. 54. @Bean 55. public MongoDbFactory secondaryFactory(MongoProperties mongo) throws Exception { 56. return new SimpleMongoDbFactory(new MongoClient(mongo.getHost(), mongo.getPort()), 57. mongo.getDatabase()); 58. } 59. } • 创建两个库分别对应的对象和Repository 对应的Mongo的对象 1. package com.gemantic.model.primary; 2. 3. import lombok.AllArgsConstructor; 4. import lombok.Data; 5. import lombok.NoArgsConstructor; 6. import org.springframework.data.annotation.Id; 7. import org.springframework.data.mongodb.core.mapping.Document; 8. 9. @Data 10. @AllArgsConstructor 11. @NoArgsConstructor 12. @Document(collection = "first_mongo") 13. public class PrimaryMongoObject { 14. 15. @Id 16. private String id; 17. 18. private String value; 19. 20. } 对应的Repository,继承了 MongoRepository 会默认实现很多基本的增删改查,省了很多自己写dao层的代码 1. public interface PrimaryRepository extends MongoRepository<PrimaryMongoObject, String> { 2. } • 主类,注意上面的注解 3. package com.gemantic; 4. 5. import com.gemantic.config.props.MultipleMongoProperties; 6. import org.springframework.boot.SpringApplication; 7. import org.springframework.boot.autoconfigure.EnableAutoConfiguration; 8. import org.springframework.boot.autoconfigure.SpringBootApplication; 9. import org.springframework.boot.autoconfigure.mongo.MongoAutoConfiguration; 10. import org.springframework.boot.context.properties.EnableConfigurationProperties; 11. import org.springframework.scheduling.annotation.EnableScheduling; 12. 13. @EnableConfigurationProperties(MultipleMongoProperties.class) 14. @SpringBootApplication(exclude = MongoAutoConfiguration.class) 15. public class Application { 16. 17. public static void main(String[] args) { 18. SpringApplication.run(Application.class, args); 19. } 20. } • 测试 21. @RunWith(SpringRunner.class) 22. @SpringBootTest 23. public class MuliDatabaseTest { 24. 25. @Autowired 26. private PrimaryRepository primaryRepository; 27. 28. @Autowired 29. private SecondaryRepository secondaryRepository; 30. 31. @Test 32. public void TestSave() { 33. 34. this.primaryRepository.save(new PrimaryMongoObject(null, "第一个库的对象")); 35. 36. this.secondaryRepository.save(new SecondaryMongoObject(null, "第二个库的对象")); 37. 38. } 39. 40. @Test 41. public void TestFindAll() { 42. 43. List<PrimaryMongoObject> primaries = this.primaryRepository.findAll(); 44. for (PrimaryMongoObject primary : primaries) { 45. System.out.println(primary.toString()); 46. } 47. 48. List<SecondaryMongoObject> secondaries = this.secondaryRepository.findAll(); 49. 50. for (SecondaryMongoObject secondary : secondaries) { 51. System.out.println(secondary.toString()); 52. } 53. } 54. 55. }
- springboot 依赖版本,1.5.3.RELEASE及以上
<parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>1.5.3.RELEASE</version> <relativePath/> <!-- lookup parent from repository --> </parent>
- 启动类上的注解
@EnableConfigurationProperties(MultipleMongoProperties.class) @SpringBootApplication(exclude = MongoAutoConfiguration.class) public class Application { public static void main(String[] args) { SpringApplication.run(Application.class, args); } }