首先
版本号是:
spring:4.3.7.RELEASE
mongoDB:1.8.4.RELEASE
接着
新增MongoDB的Spring配置文件
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-4.2.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-4.2.xsd"> <context:property-placeholder location="classpath:mongodb.properties" /> <mongo:mongo id="mongo" replica-set="${mongo.hostport}"> <!-- 一些连接属性的设置 --> <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> <!--<bean id="userCredentials" class="org.springframework.data.authentication.UserCredentials"> <constructor-arg name="username" value="${mongo.username}" /> <constructor-arg name="password" value="${mongo.password}" /> </bean>--> <bean id="mongoDbFactory" class="org.springframework.data.mongodb.core.SimpleMongoDbFactory"> <constructor-arg ref="mongo" /> <constructor-arg value="${mongo.database}" /> <!-- <constructor-arg ref="userCredentials" /> --> </bean> <bean id="mongoTemplate" class="org.springframework.data.mongodb.core.MongoTemplate"> <constructor-arg name="mongoDbFactory" ref="mongoDbFactory" /> </bean> <!-- 映射转换器,扫描back-package目录下的文件,根据注释,把它们作为mongodb的一个collection的映射 --> <mongo:mapping-converter base-package="com.xx.cc.model"/> <!-- mongodb bean的仓库目录,会自动扫描扩展了MongoRepository接口的接口进行注入 --> <mongo:repositories base-package="com.xx.cc.repository"/> </beans>
mongodb.properties
#mongoDB连接配置 mongo.hostport=IP:端口 mongo.connectionsPerHost=8 mongo.threadsAllowedToBlockForConnectionMultiplier=4 #连接超时时间 mongo.connectTimeout=1000 #等待时间 mongo.maxWaitTime=1500 mongo.autoConnectRetry=true mongo.socketKeepAlive=true #Socket超时时间 mongo.socketTimeout=1500 mongo.slaveOk=true #数据库名称 mongo.database=库名web.xml里面添加
classpath*:config/biz/mongodb.xml
或者在context.xml里面引用上mongodb.xml
com.xx.cc.model包里创建与库中collections对应的实体
package com.xx.cc.model; import org.springframework.data.annotation.Id; import org.springframework.data.mongodb.core.mapping.Document; /** * @author caosi * @create 2018-07-04 16:12 **/ @Document(collection="user") public class TestUser{ @Id private String id; private String name; private Integer age; private String custId; private String sex; public String getId() { return id; } public void setId(String id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Integer getAge() { return age; } public void setAge(Integer age) { this.age = age; } public String getCustId() { return custId; } public void setCustId(String custId) { this.custId = custId; } public String getSex() { return sex; } public void setSex(String sex) { this.sex = sex; } }
com.xx.cc.repository包中添加访问库的通用方法接口
package com.xx.cc.repository; import com.xx.cc.model.TestUser; import org.springframework.data.mongodb.repository.MongoRepository; /** * @author caosi * @create 2018-07-04 16:18 **/ public interface TestRepository extends MongoRepository<TestUser,String> { }
接着就可以使用了
@Controller public class TestController { @Autowired TestRepository testRepository; @Autowired private MongoOperations mongo; @RequestMapping("/mongodb/save") @ResponseBody public JSONObject save() { TestUser user = new TestUser(); user.setAge(66); user.setCustId(String.valueOf(System.currentTimeMillis())); user.setName("测试"); user.setSex("人妖"); testRepository.save(user); return queryAll(); } @RequestMapping("/mongodb/remove") @ResponseBody public JSONObject remove() { Criteria where=Criteria.where("sex").is("人妖"); Query query=Query.query(where); List<TestUser> list = mongo.find(query,TestUser.class); if(list!=null&&!list.isEmpty()){ testRepository.delete(list.get(0)); } return queryAll(); } @RequestMapping("/mongodb/update") @ResponseBody public JSONObject update() { Criteria where=Criteria.where("sex").is("人妖"); Query query=Query.query(where); List<TestUser> list = mongo.find(query,TestUser.class); if(list!=null&&!list.isEmpty()){ mongo.updateMulti(query, Update.update("sex","真男人"),TestUser.class); } return queryAll(); } @RequestMapping("/mongodb/queryAll") @ResponseBody public JSONObject queryAll() { List<TestUser> list = testRepository.findAll(); JSONObject object = new JSONObject(); object.put("result",list); System.out.println(list); return object; } @RequestMapping("/mongodb/queryPage/{page}") @ResponseBody public JSONObject queryPage(@PathVariable("page") Integer page) { int start = page-2; Page<TestUser> pages = testRepository.findAll(new PageRequest(start, page)); JSONObject object = new JSONObject(); object.put("result",pages); System.out.println(pages); return object; } }