Spring Data MongoDB 整合CRUD操作
一.简介
Spring Data MongoDB 项目提供与MongoDB文档数据库的集成。Spring Data MongoDB POJO的关键功能区域为中心的模型与MongoDB的DBCollection轻松地编写一个存储库交互数据访问。
二.Spring Data MongoDB的配置以及下载对应的Jar
1.安装MongoDb数据库,我们在上一篇就已经介绍过了,这边就不在介绍了,MongoDB 入门(安装与配置)
2.下载spring的spring-data的子项目两个jar,分别是spring-data-commons和spring-data-mongodb
http://projects.spring.io/spring-data-mongodb/
我这边下载是两个jar分别是:
spring-data-commons-1.7.2.RELEASE.jar
spring-data-mongodb-1.4.2.RELEASE.jar
3.下载mongoDb的java驱动jar包
http://central.maven.org/maven2/org/mongodb/mongo-java-driver/
这边有很多版本,下载自己对应得版本,我下载是:
mongo-java-driver-2.9.3.jar
4.用Java测试一下MongoDB是否能正常连接
public class TestMongodb { @Test public void testMongodb() { try{ // 连接到 mongodb 服务 Mongo mongo = new Mongo("127.0.0.1", 27017); //根据mongodb数据库的名称获取mongodb对象 , DB db = mongo.getDB( "test" ); Set<String> collectionNames = db.getCollectionNames(); // 打印出test中的集合 for (String name : collectionNames) { System.out.println("collectionName==="+name); } }catch(Exception e){ e.printStackTrace(); }运行能获取test数据库下的集合,说明能正常连接数据库
5.Spring的配置文件
1)applicationContext-mongo.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:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:util="http://www.springframework.org/schema/util" 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.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd"> <context:component-scan base-package="com.mongo" /> <!-- 获取配置资源 --> <context:property-placeholder location="classpath:jdbc.properties" /> <bean class="cn.mongo.util.SpringContextUtil"></bean> <mongo:mongo id="mongo" replica-set="${mongo.replicaSet}"> <!-- connections-per-host: 每个主机答应的连接数(每个主机的连接池大小),当连接池被用光时,会被阻塞住 max-wait-time: 被阻塞线程从连接池获取连接的最长等待时间(ms) connect-timeout:在建立(打开)套接字连接时的超时时间(ms) socket-timeout:套接字超时时间;该值会被传递给Socket.setSoTimeout(int) slave-ok:指明是否答应驱动从次要节点或者奴隶节点读取数据 --> <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="${mongo.writeNumber}" write-timeout="${mongo.riteTimeout}" write-fsync="${mongo.writeFsync}"/> </mongo:mongo> <!-- 设置使用的数据库 名--> <mongo:db-factory dbname="test" mongo-ref="mongo"/> <!-- mongodb的模板 --> <bean id="mongoTemplate" class="org.springframework.data.mongodb.core.MongoTemplate"> <constructor-arg name="mongoDbFactory" ref="mongoDbFactory"/> </bean> </beans>
2)jdbc.properties
mongo.replicaSet=127.0.0.1:27017 mongo.connectionsPerHost=8 mongo.threadsAllowedToBlockForConnectionMultiplier=4 mongo.connectTimeout=1000 mongo.maxWaitTime=1500 mongo.autoConnectRetry=true mongo.socketKeepAlive=true mongo.socketTimeout=1500 mongo.slaveOk=true mongo.writeNumber=1 mongo.riteTimeout=0 mongo.writeFsync=true说明:
我们可以上官方网查看文档http://docs.spring.io/spring-data/data-mongo/docs/1.7.0.RC1/reference/html/#mongodb-connectors,这里面有说明怎么配置
三.Spring 实现MongoDB的CRUD操作
1.实现一个基础接口,是比较通用的 MongoBase.java类
public interface MongoBase<T> { //添加 public void insert(T object,String collectionName); //根据条件查找 public T findOne(Map<String,Object> params,String collectionName); //查找所有 public List<T> findAll(Map<String,Object> params,String collectionName); //修改 public void update(Map<String,Object> params,String collectionName); //创建集合 public void createCollection(String collectionName); //根据条件删除 public void remove(Map<String,Object> params,String collectionName); }
2.实现一个实体类,我这边实现了User类
@Document注解,表示这个POJO最终要持久化为MongoDB中的document
@Document public class User implements Serializable { /** * */ private static final long serialVersionUID = 1L; private String id; private String name; private int age; private String password; public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public String getId() { return id; } public void setId(String id) { this.id = id; } }
3.实现UserDao类,就是实现User自己操作数据库的接口,这个UserDao也继承了MongoBase接口,我们这边UserDao没实现其他额外的接口
public interface UserDao extends MongoBase<User>{ }
4.实现UserDaoImpl具体类,这边是实际操作数据库
@Repository("userDaoImpl") public class UserDaoImpl implements UserDao { @Resource private MongoTemplate mongoTemplate; @Override public void insert(User object,String collectionName) { mongoTemplate.insert(object, collectionName); } @Override public User findOne(Map<String,Object> params,String collectionName) { return mongoTemplate.findOne(new Query(Criteria.where("id").is(params.get("id"))), User.class,collectionName); } @Override public List<User> findAll(Map<String,Object> params,String collectionName) { List<User> result = mongoTemplate.find(new Query(Criteria.where("age").lt(params.get("maxAge"))), User.class,collectionName); return result; } @Override public void update(Map<String,Object> params,String collectionName) { mongoTemplate.upsert(new Query(Criteria.where("id").is(params.get("id"))), new Update().set("name", params.get("name")), User.class,collectionName); } @Override public void createCollection(String name) { mongoTemplate.createCollection(name); } @Override public void remove(Map<String, Object> params,String collectionName) { mongoTemplate.remove(new Query(Criteria.where("id").is(params.get("id"))),User.class,collectionName); }
说明:
我们可以上官方网查看文档http://docs.spring.io/spring-data/data-mongo/docs/1.7.0.RC1/reference/html/#mongodb-connectors
mongoTemplate.upsert
这边update里面提供了很多功能,可以根据条件进行修改,Criteria这个类也提供了where 、and、lt等,我们在查询年龄大于30的查出来,mongoTemplate.find(new Query(Criteria.where("age").lt(params.get("maxAge"))), User.class,collectionName);Criteria还很多
如图所示:
4.实现测试类
我们这边为了节省时间,就没写服务类,我们直接调用dao就可以了,实现了TestUser.java类
1)添加并根据条件查找列表
public class TestUser { private static UserDao userDaoImpl; private static ClassPathXmlApplicationContext app; private static String collectionName; @BeforeClass public static void initSpring() { try { app = new ClassPathXmlApplicationContext(new String[] { "classpath:applicationContext-mongo.xml", "classpath:spring-dispatcher.xml" }); userDaoImpl = (UserDao) app.getBean("userDaoImpl"); collectionName ="users"; } catch (Exception e) { e.printStackTrace(); } } @Test public void testAdd() { //添加一百个user for(int i=0;i<100;i++){ User user =new User(); user.setId(""+i); user.setAge(i); user.setName("zcy"+i); user.setPassword("zcy"+i); userDaoImpl.insert(user,collectionName); } Map<String,Object> params=new HashMap<String,Object>(); params.put("maxAge", 50); List<User> list=userDaoImpl.findAll(params,collectionName); System.out.println("user.count()=="+list.size()); }运行一下,我们能正常查找年龄大于50的
2)根据ID进行修改
@Test public void testUdate(){ Map<String,Object> params=new HashMap<String,Object>(); params.put("id", "1"); User user=userDaoImpl.findOne(params, collectionName); System.out.println("user.name==="+user.getName()); System.out.println("=============update=================="); params.put("name", "hello"); userDaoImpl.update(params, collectionName); user=userDaoImpl.findOne(params, collectionName); System.out.println("user.name==="+user.getName()); }
3)根据ID删除对应的数据
@Test public void testRemove(){ Map<String,Object> params=new HashMap<String,Object>(); params.put("id", "2"); userDaoImpl.remove(params, collectionName); User user=userDaoImpl.findOne(params, collectionName); System.out.println("user=="+user); }
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。