MongoDB和Java(4):Spring Data整合MongoDB(XML配置)
最近花了一些时间学习了下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副本集、分片集群
本文记录如何使用XML配置方式整合Spring data和MongoDB
源代码下载
MongoDB和Java学习代码.zip
1、环境准备
JDK 1.8
Spring 4.2.5.RELEASE
Junit 4.10
Spring-data-mongodb 1.9.0.RELEASE
Logback 1.1.7
Maven 3.2.1
依赖
1 <properties> 2 <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> 3 <maven.compiler.source>1.8</maven.compiler.source> 4 <maven.compiler.target>1.8</maven.compiler.target> 5 <spring.version>4.2.5.RELEASE</spring.version> 6 </properties> 7 8 <dependencies> 9 10 <dependency> 11 <groupId>junit</groupId> 12 <artifactId>junit</artifactId> 13 <version>4.10</version> 14 <scope>test</scope> 15 </dependency> 16 17 <dependency> 18 <groupId>org.springframework</groupId> 19 <artifactId>spring-context-support</artifactId> 20 <version>${spring.version}</version> 21 </dependency> 22 <dependency> 23 <groupId>org.springframework</groupId> 24 <artifactId>spring-aop</artifactId> 25 <version>${spring.version}</version> 26 </dependency> 27 <dependency> 28 <groupId>org.springframework</groupId> 29 <artifactId>spring-test</artifactId> 30 <version>${spring.version}</version> 31 <scope>test</scope> 32 </dependency> 33 34 <dependency> 35 <groupId>org.springframework.data</groupId> 36 <artifactId>spring-data-mongodb</artifactId> 37 <version>1.9.0.RELEASE</version> 38 </dependency> 39 40 <!-- logback日志 --> 41 <dependency> 42 <groupId>ch.qos.logback</groupId> 43 <artifactId>logback-core</artifactId> 44 <version>1.1.7</version> 45 </dependency> 46 <dependency> 47 <groupId>ch.qos.logback</groupId> 48 <artifactId>logback-classic</artifactId> 49 <version>1.1.7</version> 50 </dependency> 51 <dependency> 52 <groupId>org.aspectj</groupId> 53 <artifactId>aspectjweaver</artifactId> 54 <version>1.6.1</version> 55 </dependency> 56 57 </dependencies> 58 59 <build> 60 <finalName>security-demo</finalName> 61 <plugins> 62 <plugin> 63 <groupId>org.apache.maven.plugins</groupId> 64 <artifactId>maven-compiler-plugin</artifactId> 65 <version>3.3</version> 66 <configuration> 67 <source>${maven.compiler.source}</source> 68 <target>${maven.compiler.target}</target> 69 <encoding>${project.build.sourceEncoding}</encoding> 70 </configuration> 71 </plugin> 72 </plugins> 73 </build>
2、mongodb配置文件
这个是spring的子配置文件,通过从.properties文件读取连接属性创建mongoClient对象,再创建DBFactory对象,通过DBFactory创建MongoTemplate,我们的数据层实现类就是使用MongoTemplate操作MongoDB的。
1 <?xml version="1.0" encoding="UTF-8"?> 2 <beans xmlns="http://www.springframework.org/schema/beans" 3 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 4 xmlns:context="http://www.springframework.org/schema/context" 5 xmlns:mongo="http://www.springframework.org/schema/data/mongo" 6 xsi:schemaLocation="http://www.springframework.org/schema/beans 7 http://www.springframework.org/schema/beans/spring-beans-4.2.xsd 8 http://www.springframework.org/schema/context 9 http://www.springframework.org/schema/context/spring-context-4.2.xsd 10 http://www.springframework.org/schema/data/mongo 11 http://www.springframework.org/schema/data/mongo/spring-mongo-1.8.xsd"> 12 13 <!-- 连接属性文件,配置服务器IP端口、数据库和连接参数 --> 14 <context:property-placeholder location="classpath:mongodb.properties" 15 ignore-unresolvable="true" /> 16 17 <!-- 创建MongoClient --> 18 <mongo:mongo-client id="mongo" replica-set="${mongo.hostport}"> 19 <mongo:client-options connections-per-host="${mongo.connectionsPerHost}" 20 threads-allowed-to-block-for-connection-multiplier= 21 "${mongo.threadsAllowedToBlockForConnectionMultiplier}" 22 connect-timeout="${mongo.connectTimeout}" max-wait-time="${mongo.maxWaitTime}" 23 socket-keep-alive="${mongo.socketKeepAlive}" 24 socket-timeout="${mongo.socketTimeout}" /> 25 </mongo:mongo-client> 26 27 <!-- MongoDbFactory --> 28 <mongo:db-factory id="mgFactory" dbname="${mongo.dbname}" 29 mongo-ref="mongo" /> 30 31 <!-- MongoTemplate --> 32 <bean id="mongoTemplate" class="org.springframework.data.mongodb.core.MongoTemplate"> 33 <constructor-arg name="mongoDbFactory" ref="mgFactory" /> 34 </bean> 35 36 </beans>
mongodb.properties
1 mongo.hostport=10.10.12.195:27017 2 mongo.dbname=test 3 mongo.connectionsPerHost=8 4 mongo.threadsAllowedToBlockForConnectionMultiplier=4 5 mongo.connectTimeout=1000 6 mongo.maxWaitTime=1500 7 mongo.socketKeepAlive=true 8 mongo.socketTimeout=1500
3、spring主配置文件
application.xml是spring的主配置文件,配置组件扫描,另外还要引入mongo的配置
1 <?xml version="1.0" encoding="UTF-8"?> 2 <beans xmlns="http://www.springframework.org/schema/beans" 3 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 4 xmlns:context="http://www.springframework.org/schema/context" 5 xmlns:tx="http://www.springframework.org/schema/tx" 6 xmlns:aop="http://www.springframework.org/schema/aop" 7 xsi:schemaLocation="http://www.springframework.org/schema/beans 8 http://www.springframework.org/schema/beans/spring-beans-4.2.xsd 9 http://www.springframework.org/schema/context 10 http://www.springframework.org/schema/context/spring-context-4.2.xsd"> 11 12 <!-- 组件扫描 --> 13 <context:component-scan base-package="org.net5ijy.mongo.dao" /> 14 <!--使用注解管理bean --> 15 <context:annotation-config /> 16 17 <import resource="application-mongo.xml" /> 18 19 </beans>
4、实体类和数据层
Employee
1 @Document(collection = "employee") 2 public class Employee implements Serializable { 3 4 @Id 5 @Field(value = "_id") 6 private String id; 7 8 @Field(value = "name") 9 private String name; 10 11 @Field 12 private Integer age; 13 14 @Field 15 private Date createTime = new Date(); 16 17 public Employee() { 18 super(); 19 } 20 public Employee(String name, Integer age) { 21 super(); 22 this.name = name; 23 this.age = age; 24 } 25 26 // getter & setter 27 }
数据层实现
1 @Repository 2 public class EmployeeDaoImpl implements EmployeeDao { 3 4 @Autowired 5 private MongoTemplate mongoTemplate; 6 7 @Override 8 public List<Employee> findAll() { 9 return mongoTemplate.findAll(Employee.class); 10 } 11 12 @Override 13 public void insertOneEmployee(Employee employee) { 14 mongoTemplate.insert(employee); 15 } 16 17 @Override 18 public void deleteOneEmployeeByName(String name) { 19 Criteria c = new Criteria(); 20 c.and("name").is(name); 21 Query query = new Query(c); 22 mongoTemplate.remove(query, Employee.class); 23 } 24 25 @Override 26 public void deleteOneEmployee(String id) { 27 Criteria c = new Criteria(); 28 c.and("_id").is(id); 29 Query query = new Query(c); 30 mongoTemplate.remove(query, Employee.class); 31 } 32 33 @Override 34 public Employee findByName(String name) { 35 Criteria c = new Criteria(); 36 c.and("name").is(name); 37 Query query = new Query(c); 38 return mongoTemplate.findOne(query, Employee.class); 39 } 40 41 @Override 42 public Employee find(String id) { 43 return mongoTemplate.findById(id, Employee.class); 44 } 45 }
代码中把MongoTemplate注入到了实现类,然后使用它的API进行数据库操作。
5、Junit测试类
1 @RunWith(SpringJUnit4ClassRunner.class) 2 @ContextConfiguration(locations = { "classpath:application.xml" }) 3 public class EmployeeDaoImplTest { 4 5 @Autowired 6 private EmployeeDao employeeDao; 7 8 @Autowired 9 private ApplicationContext context; 10 11 @Test 12 public void testFindAll() { 13 List<Employee> list = employeeDao.findAll(); 14 for (Employee employee : list) { 15 System.out.println(employee); 16 } 17 } 18 19 @Test 20 public void testInsertOneEmployee() { 21 Employee e = new Employee("admin", 28); 22 employeeDao.insertOneEmployee(e); 23 } 24 25 @Test 26 public void testDeleteOneEmployeeByName() { 27 employeeDao.deleteOneEmployeeByName("admin"); 28 } 29 30 @Test 31 public void testDeleteOneEmployee() { 32 Employee e = employeeDao.findByName("admin"); 33 employeeDao.deleteOneEmployee(e.getId()); 34 } 35 36 @Test 37 public void testFindByName() { 38 Employee e = employeeDao.findByName("admin"); 39 System.out.println(e); 40 } 41 42 @Test 43 public void testFind() { 44 Employee e = employeeDao.findByName("admin"); 45 Employee e2 = employeeDao.find(e.getId()); 46 System.out.println(e2); 47 } 48 }
6、参考资料
Spring Data MongoDB - Reference Documentation
https://docs.spring.io/spring-data/mongodb/docs/1.10.15.RELEASE/reference/html/