下面只是测试有用,一般情况下可以用来存日志的。
然后把下面的增删改查放dao层跟掉数据库相类似。然后建service层来调用
1.导包。注意版本,
<!-- spring data mongoDB依赖 --> <dependency> <groupId>org.springframework.data</groupId> <artifactId>spring-data-mongodb</artifactId> <version>1.8.4.RELEASE</version> </dependency> <dependency> <groupId>org.mongodb</groupId> <artifactId>mongo-java-driver</artifactId> <version>3.2.2</version> </dependency>
2 spring-mongodb.xml 配置文件
无法将名称 'repository:auditing-attributes' 解析为 'attribute group' 组件
出现这个错误是没有添加http://www.springframework.org/schema/data/repository http://www.springframework.org/schema/data/repository/spring-repository-1.5.xsd
Usage of 'mongo-options' is no longer supported for MongoDB Java driver version 3 and above. Please use 'mongo-client-options' and refer to chapter 'MongoDB 3.0 Support' for details
mongodb 3.0开始需要定义mongo:mongo-client,而不是mongo:mongo
<?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:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:util="http://www.springframework.org/schema/util" xmlns:repository="http://www.springframework.org/schema/data/repository" xmlns:context="http://www.springframework.org/schema/context" xmlns:mongo="http://www.springframework.org/schema/data/mongo" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.0.xsd http://www.springframework.org/schema/data/mongo http://www.springframework.org/schema/data/mongo/spring-mongo-1.8.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd http://www.springframework.org/schema/data/repository http://www.springframework.org/schema/data/repository/spring-repository-1.5.xsd"> <context:annotation-config /> <context:component-scan base-package="com.spring.redis.controller" /> <bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"> <property name="locations"> <list> <value>classpath:conf/mongoDB.properties</value> </list> </property> </bean> <!--连接池配置--> <mongo:mongo-client host="${mongo.host}" port="${mongo.port}"> <mongo:client-options connections-per-host="${mongo.options.connections-per-host}" threads-allowed-to-block-for-connection-multiplier="${mongo.options.threads-allowed-to-block-for-connection-multiplier}" connect-timeout="${mongo.options.connect-timeout}" max-wait-time="${mongo.options.max-wait-time}" socket-keep-alive="${mongo.options.socket-keep-alive}" socket-timeout="${mongo.options.socket-timeout}"/> </mongo:mongo-client> <!--连接池工厂配置 <mongo:db-factory dbname="${mongo.dbname}" username="${mongo.username}" password="${mongo.password}" mongo-ref="mongo"/> --> <mongo:db-factory dbname="${mongo.dbname}" mongo-ref="mongo"/> <bean id="mongoTemplate" class="org.springframework.data.mongodb.core.MongoTemplate"> <constructor-arg name="mongoDbFactory" ref="mongoDbFactory"/> </bean> </beans>
3. mongoDB.properties
mongo.host=192.168.88.134 mongo.port=27017 mongo.dbname=guilf1 #mongo.username=username #mongo.password=password mongo.options.connections-per-host=20 mongo.options.threads-allowed-to-block-for-connection-multiplier=4 mongo.options.connect-timeout=1000 mongo.options.max-wait-time=1500 mongo.options.auto-connect-retry=false mongo.options.socket-keep-alive=true mongo.options.socket-timeout=1500 mongo.options.slave-ok=false mongo.options.write-number=1 mongo.options.write-timeout=0 mongo.options.write-fsync=true
4.User.java
package com.spring.redis.controller; public class User{ private int id; private String name; private Integer age; public int getUserId() { return id; } public void setId(int 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; } @Override public String toString() { return "User{" + "id=" + id + ", name='" + name + '\'' + ", age=" + age + '}'; } }
5.
package com.spring.redis.controller; import java.util.ArrayList; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.support.ClassPathXmlApplicationContext; import org.springframework.data.mongodb.core.MongoTemplate; import org.springframework.data.mongodb.core.query.Criteria; import org.springframework.data.mongodb.core.query.Query; import org.bson.Document; import org.junit.Before; import org.junit.Test; import static org.springframework.data.mongodb.core.query.Criteria.where; public class SpringMongoDBController { @Autowired private MongoTemplate mongoTemplate; @Before public void testBefore() { ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("classpath:conf/spring-mongodb.xml"); mongoTemplate = (MongoTemplate) context.getBean("mongoTemplate"); } /** * 插入用户信息 */ @Test public void testAddUser() { // Document document = new Document("title1", "MongoDB1"). // append("description1", "database"). // append("likes1", 100). // append("by", "Fly"); // Document document2 = new Document("title1", "MongoDB1"). // append("description1", "databas1e"). // append("ggg1", 100). // append("by1", "Fl1y"); // List<Document> documents = new ArrayList<Document>(); // documents.add(document); // documents.add(document2); // 插入数据 // mongoTemplate.insert(document); User user1 = new User(); user1.setId(1); user1.setName("guilf"); user1.setAge(22); User user2 = new User(); user2.setId(2); user2.setName("guilf2"); user2.setAge(28); // User user2 = new User(); // user2.setName("guilf2"); // user2.setAge(22); // // List<User> users = new ArrayList<User>(); // users.add(user1); // users.add(user2); // 插入数据 mongoTemplate.insert(user1); mongoTemplate.insert(user2); } /** * 查询用户信息 */ @Test public void testQueryUser() { // 查询主要用到Query和Criteria两个对象 Query query = new Query(); Criteria criteria = where("age").gt(23); // Criteria criteria = where("age").gt(22); // 大于 // criteria.and("name").is("cuichongfei");等于 // List<String> interests = new ArrayList<String>(); // interests.add("study"); // interests.add("linux"); // criteria.and("interest").in(interests); in查询 // criteria.and("home.address").is("henan"); 内嵌文档查询 // criteria.and("").exists(false); 列存在 // criteria.and("").lte(); 小于等于 // criteria.and("").regex(""); 正则表达式 // criteria.and("").ne(""); 不等于 // 多条件查询 // criteria.orOperator(Criteria.where("key1").is("0"),Criteria.where("key1").is(null)); query.addCriteria(criteria); List<User> userList1 = mongoTemplate.find(query, User.class); System.out.println(userList1); // 排序查询sort方法,按照age降序排列 // query.sort().on("age", Order.DESCENDING); // List<User> userList2 = mongoTemplate.find(query, User.class); // printList(userList2); // Query query = new Query(); // query.with(new Sort(Direction.ASC, "priority").and(new Sort(Direction.ASC, "create_time"))); // 指定字段查询,只查询age和name两个字段 // query.fields().include("age").include("name"); // List<User> userList3 = mongoTemplate.find(query, User.class); // printList(userList3); // 分页查询 // query.skip(2).limit(3); // List<User> userList4 = mongoTemplate.find(query, User.class); // printList(userList4); // 查询所有 // printList(mongoTemplate.findAll(User.class)); // 统计数据量 // System.out.println(mongoTemplate.count(query, User.class)); } /** * 更新用户数据 */ @Test public void testUpdateUser() { // update(query,update,class) // Query query:需要更新哪些用户,查询参数 // Update update:操作符,需要对数据做什么更新 // Class class:实体类 // 更新age大于24的用户信息 Query query = new Query(); query.addCriteria(where("age").gt(24)); Update update = new Update(); // age值加2 update.inc("age", 2); // update.set("name", "zhangsan"); 直接赋值 // update.unset("name"); 删去字段 // update.push("interest", "java"); 把java追加到interest里面,interest一定得是数组 // update.pushAll("interest", new String[]{".net","mq"}) // 用法同push,只是pushAll一定可以追加多个值到一个数组字段内 // update.pull("interest", "study"); 作用和push相反,从interest字段中删除一个等于value的值 // update.pullAll("interest", new String[]{"sing","dota"})作用和pushAll相反 // update.addToSet("interest", "study") 把一个值添加到数组字段中,而且只有当这个值不在数组内的时候才增加 // update.rename("oldName", "newName") 字段重命名 // 只更新第一条记录,age加2,name值更新为zhangsan mongoTemplate.updateFirst(query, new Update().inc("age", 2).set("name", "zhangsan"), User.class); // 批量更新,更新所有查询到的数据 mongoTemplate.updateMulti(query, update, User.class); } /** * 测试删除数据 */ @Ignore @Test public void testRemoveUser() { Query query = new Query(); // query.addCriteria(where("age").gt(22)); Criteria criteria = where("age").gt(22); // 删除年龄大于22岁的用户 query.addCriteria(criteria); mongoTemplate.remove(query, User.class); } public void printList(List<User> userList) { for (User user : userList) { System.out.println(user); } } /** * 数组文档指定元素更新 */ @Test public void testUpdateDocument() { // 只更新一个内嵌文档 // Update update = new Update(); // update.set("sonModelList.$.state", 2); // mongoTemplate.updateMulti(new Query(Criteria.where("sonModelList.geoNum").is("532568248122605568")), update, CatchThirteenthModel.class); // 批量更新所有的内嵌文档 // update.set("sonModelList.$.state", 2); // mongoTemplate.updateMulti(new Query(Criteria.where("sessionId").is("cf23e870-2c5a-4d1f-9652-6fa1793dc8be")), // new Update().set("state", 2), CatchThirteenthModel.class); // mongoTemplate.updateMulti(new Query(Criteria.where("sonModelList.parentGeoNum").is("532568523000512512")), // new Update().set("state", 2), CatchFifteenthModel.class); List<CatchFifteenthModel> find = mongoTemplate.find(new Query(Criteria.where("sonModelList.parentGeoNum").is("532568523000512512")), CatchFifteenthModel.class); System.out.println(""); } /** * 测试findAndModify方法 */ @Test public void testFindAndModify() { Criteria criteria = new Criteria(); criteria.andOperator(Criteria.where("geoNum").is("526547322448904192"), Criteria.where("geoLevel").is(14)); CatchModel model = mongoTemplate.findAndModify(new Query(criteria), new Update().set("state", 2).set("endTime", new Date()), new FindAndModifyOptions().returnNew(true), CatchModel.class); System.out.println(model); } }