我自己的实现:
代码:https://github.com/littlecarzz/spring-data-mongodb
我使用的是spring-data-mongodb包,因为springboot注解和自动化配置,可以让我们少写很多配置文件,方便。
1.首先引入依赖
pom.xml
<dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.12</version> </dependency> <dependency> <groupId>org.springframework.data</groupId> <artifactId>spring-data-mongodb</artifactId> <version>2.0.14.RELEASE</version> </dependency> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-log4j12</artifactId> <version>1.7.12</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-web</artifactId> <version>5.1.7.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>5.1.7.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-test</artifactId> <version>5.1.7.RELEASE</version> </dependency> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <version>1.18.6</version> </dependency>
2.配置mongodb.properties
这里主要是配置mongodb数据库的一些参数config
#ip mongo.host=127.0.0.1 #端口 mongo.port=27017 #数据库 mongo.dbname=user #用户名 mongo.username=cjj #密码 mongo.password=123456 #一个线程变为可用的最大阻塞数 mongo.connectionsPerHost=8 #线程队列数,它以上面connectionsPerHost值相乘的结果就是线程队列最大值 mongo.threadsAllowedToBlockForConnectionMultiplier=4 #连接超时时间(毫秒) mongo.connectTimeout=1000 #最大等待时间 mongo.maxWaitTime=1500 #自动重连 mongo.autoConnectRetry=true #scoket保持活动 mongo.socketKeepAlive=true #scoket超时时间 mongo.socketTimeout=1500 #读写分离 mongo.slaveOk=true
3.配置mongodb.xml
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xmlns:mongo="http://www.springframework.org/schema/data/mongo" xsi:schemaLocation="http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd http://www.springframework.org/schema/data/mongo http://www.springframework.org/schema/data/mongo/spring-mongo-1.0.xsd http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd"> <!-- 加载mongodb的属性配置文件 --> <context:property-placeholder location="classpath:mongodb.properties" ignore-unresolvable="true"/> <!-- 定义mongo对象,对应的是mongodb官方jar包中的Mongo,设置ip地址和端口 --> <mongo:mongo id="mongo" host="${mongo.host}" port="${mongo.port}"> <mongo:options connections-per-host="${mongo.connectionsPerHost}" threads-allowed-to-block-for-connection-multiplier="${mongo.threadsAllowedToBlockForConnectionMultiplier}" connect-timeout="${mongo.connectTimeout}" max-wait-time="${mongo.maxWaitTime}" auto-connect-retry="${mongo.autoConnectRetry}" socket-keep-alive="${mongo.socketKeepAlive}" socket-timeout="${mongo.socketTimeout}" slave-ok="${mongo.slaveOk}" write-number="1" write-timeout="0" write-fsync="true"/> </mongo:mongo> <mongo:db-factory id="mgFactory" dbname="${mongo.dbname}" username="${mongo.username}" password="${mongo.password}" mongo-ref="mongo"/> <bean id="mongoTemplate" class="org.springframework.data.mongodb.core.MongoTemplate"> <constructor-arg name="mongoDbFactory" ref="mgFactory"/> </bean> </beans>
4.配置spring-context.xml
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:task="http://www.springframework.org/schema/task" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.1.xsd http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-3.1.xsd"> <aop:aspectj-autoproxy proxy-target-class="true"/> <!--使用注解管理bean --> <context:annotation-config/> <!-- 扫描com.example下的所有类 --> <context:component-scan base-package="com.example"> <context:exclude-filter type = "annotation" expression = "org.springframework.stereotype.Controller"/> </context:component-scan> <import resource="mongoDB.xml"/> </beans>
5.测试
先创建实体类User
import lombok.Data; import org.springframework.data.mongodb.core.mapping.Document; @Data @Document(collection="user") public class User { private String id; private String name; private String sex; private Integer age; }
在创建MongoDBService获取MongoTemplate
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.ApplicationContext; import org.springframework.context.annotation.Bean; import org.springframework.context.support.ClassPathXmlApplicationContext; import org.springframework.data.mongodb.core.MongoTemplate; import org.springframework.data.mongodb.core.query.Query; import org.springframework.stereotype.Service; import javax.annotation.Resource; @Service("mongoDBService") public class MongoDBService { @Resource(name = "mongoTemplate") private MongoTemplate mongoTemplate; public <T> T findOne(Query query, Class<T> entityClass){ ApplicationContext context=new ClassPathXmlApplicationContext("mongoDB.xml"); // MongoTemplate mongoTemplate= (MongoTemplate) context.getBean("mongoTemplate"); // 可以直接调用 return mongoTemplate.findOne(query, entityClass); } }
然后创建UserService继承MongoDBService
import com.example.entity.User; import org.springframework.data.mongodb.core.query.Criteria; import org.springframework.data.mongodb.core.query.Query; import org.springframework.stereotype.Service; @Service public class UserService extends MongoDBService { public User findUserByName(String name){ Criteria criteria = new Criteria(); criteria.andOperator(Criteria.where("name").is("cjj")); Query query = new Query(criteria); return findOne(query, User.class); } }
最后测试
import com.example.entity.User; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import javax.annotation.Resource; @ContextConfiguration({ "classpath:spring-context.xml", "classpath:mongoDB.xml"}) @RunWith(SpringJUnit4ClassRunner.class) public class UserServiceTest { @Resource(name = "userService") private UserService userService; @Test public void test(){ User user = userService.findUserByName("cjj"); System.out.println(user); } }
其他实现: