最近花了一些时间学习了下MongoDB数据库,感觉还是比较全面系统的,涉及了软件安装、客户端操作、安全认证、副本集和分布式集群搭建,以及使用Spring Data连接MongoDB进行数据操作,收获很大。特此记录,以备查看。
文章目录:
MongoDB和Java(1):Linux下的MongoDB安装
MongoDB和Java(2):普通用户启动mongod进程
MongoDB和Java(4):Spring Data整合MongoDB(XML配置)
MongoDB和Java(5):Spring Data整合MongoDB(注解配置)
MongoDB和Java(6):Spring Data整合MongoDB副本集、分片集群
本文记录如何使用注解配置方式整合Spring data和MongoDB,基础的环境和使用xml整合是一样的,不同的是:
1)删除spring的xml配置文件
2)不再编写数据层的实现,而是使用Spring Data Mongodb扫描创建代理实现
源代码下载
MongoDB和Java学习代码.zip
1、MongoProperties类
这个类用于读取mongo.properties中属性
1 @Component 2 @PropertySource(value = "classpath:mongodb.properties") 3 public class MongoProperties { 4 5 @Value("${mongo.host}") 6 private String host; 7 8 @Value("${mongo.port}") 9 private Integer port; 10 11 @Value("${mongo.dbname}") 12 private String dbname; 13 14 @Value("${mongo.username}") 15 private String username; 16 17 @Value("${mongo.password}") 18 private String password; 19 20 @Value("${mongo.connectionsPerHost}") 21 private int connectionsPerHost; 22 23 @Value("${mongo.minConnectionsPerHost}") 24 private int minConnectionsPerHost; 25 26 @Value("${mongo.threadsAllowedToBlockForConnectionMultiplier}") 27 private int threadsAllowedToBlockForConnectionMultiplier; 28 29 @Value("${mongo.connectTimeout}") 30 private int connectTimeout; 31 32 @Value("${mongo.maxWaitTime}") 33 private int maxWaitTime; 34 35 @Value("${mongo.socketKeepAlive}") 36 private boolean socketKeepAlive; 37 38 @Value("${mongo.socketTimeout}") 39 private int socketTimeout; 40 41 // getter & setter 42 }
mongo.properties文件
1 mongo.host=10.10.13.195 2 mongo.port=27017 3 4 # 数据库和验证信息 5 mongo.dbname=test 6 mongo.username=xugf 7 mongo.password=123456 8 9 mongo.connectionsPerHost=8 10 mongo.minConnectionsPerHost=3 11 mongo.threadsAllowedToBlockForConnectionMultiplier=4 12 mongo.connectTimeout=1000 13 mongo.maxWaitTime=1500 14 mongo.socketKeepAlive=true 15 mongo.socketTimeout=1500
2、MongoConfiguration配置类
这个类用于配置MongoClient和DbFactory
我们参考下官方文档,https://github.com/spring-projects/spring-data-mongodb
1)配置类继承AbstractMongoConfiguration
2)使用@EnableMongoRepositories注解开启MongoRepsitory的扫描功能
看下这个类的代码
1 @EnableMongoRepositories(basePackages = "org.net5ijy.mongo.dao") 2 @Configuration 3 @ComponentScan(basePackages = { "org.net5ijy.mongo" }) 4 public class MongoConfiguration extends AbstractMongoConfiguration { 5 6 @Autowired 7 private MongoProperties mongoProperties; 8 9 public MongoClient mongoClient() throws Exception { 10 11 // 获取单机服务器环境 12 ServerAddress address = new ServerAddress(mongoProperties.getHost(), 13 mongoProperties.getPort()); 14 15 List<MongoCredential> credentialsList = new ArrayList<MongoCredential>(); 16 credentialsList.add(MongoCredential.createScramSha1Credential( 17 mongoProperties.getUsername(), mongoProperties.getDbname(), 18 mongoProperties.getPassword().toCharArray())); 19 20 Builder builder = MongoClientOptions.builder(); 21 22 builder.connectionsPerHost(mongoProperties.getConnectionsPerHost()); 23 builder.threadsAllowedToBlockForConnectionMultiplier(mongoProperties 24 .getThreadsAllowedToBlockForConnectionMultiplier()); 25 builder.connectTimeout(mongoProperties.getConnectTimeout()); 26 builder.maxWaitTime(mongoProperties.getMaxWaitTime()); 27 builder.socketKeepAlive(mongoProperties.isSocketKeepAlive()); 28 builder.socketTimeout(mongoProperties.getSocketTimeout()); 29 builder.minConnectionsPerHost(mongoProperties 30 .getMinConnectionsPerHost()); 31 32 return new MongoClient(address, credentialsList, builder.build()); 33 } 34 35 @Bean 36 public static PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer() { 37 return new PropertySourcesPlaceholderConfigurer(); 38 } 39 40 @Override 41 protected String getDatabaseName() { 42 return mongoProperties.getDbname(); 43 } 44 45 @Override 46 public Mongo mongo() throws Exception { 47 return mongoClient(); 48 } 49 }
3、数据层接口
继承MongoRepository
1 public interface EmployeeDao extends MongoRepository<Employee, String> { 2 3 void deleteByName(String name); 4 5 Employee findByName(String name); 6 }
4、JUnit测试代码
1 @RunWith(SpringJUnit4ClassRunner.class) 2 @ContextConfiguration(classes = { MongoConfiguration.class }) 3 public class EmployeeDaoTest { 4 5 @Autowired 6 private EmployeeDao employeeDao; 7 8 @Autowired 9 private ConfigurableApplicationContext context; 10 11 @Test 12 public void testFindAll() throws Exception { 13 14 System.out.println(" ##### ApplicationContext class ##### "); 15 16 System.out.println(context.getClass()); 17 18 System.out.println(" ##### Object names ##### "); 19 20 String[] names = context.getBeanDefinitionNames(); 21 for (String name : names) { 22 System.out.println(name); 23 } 24 25 System.out.println(" ##### MongoDB employees ##### "); 26 27 List<Employee> list = employeeDao.findAll(); 28 for (Employee employee : list) { 29 System.out.println(employee); 30 } 31 32 // Thread.sleep(10000); 33 34 context.close(); 35 } 36 37 @Test 38 public void testSave() { 39 Employee e = new Employee("admin", 28); 40 e.setSalary(4234.56); 41 employeeDao.save(e); 42 } 43 44 @Test 45 public void testDeleteByName() { 46 employeeDao.deleteByName("admin"); 47 } 48 49 @Test 50 public void testDelete() { 51 Employee e = employeeDao.findByName("admin"); 52 employeeDao.delete(e.getId()); 53 } 54 55 @Test 56 public void testFindByName() { 57 Employee e = employeeDao.findByName("admin"); 58 System.out.println(e); 59 } 60 61 @Test 62 public void testFindOne() { 63 Employee e = employeeDao.findByName("admin"); 64 Employee e2 = employeeDao.findOne(e.getId()); 65 System.out.println(e2); 66 } 67 }
和xml配置时编写的测试类区别不大,就是
@ContextConfiguration(classes = { MongoConfiguration.class })
这里有了变化
5、扩展:MongoDB添加用户
1 use admin 2 db.createUser({user: "admin", pwd: "123456", roles:[{role: "root", db: "admin" }]}) 3 4 use test 5 db.createUser({user: "xugf", pwd:"123456", roles:[{role:"dbOwner", db:"test"}]})
6、参考资料
Spring Data MongoDB
https://github.com/spring-projects/spring-data-mongodb