SpringDataMongodb系列教程1--XML配置搭建环境

2017-12-26 19:21:41来源:CSDN作者:wang258533488人点击

分享

1 概述

SpringDataMongodb是Spring对mongodb客户端的封装,本文将讲述如何通过XML配置的方式在项目中使用mongodb。

2 引入pom依赖

2.1 本文所用的依赖版本

Spring:4.3.13
mongodb:3.4.10
spring-data-mongodb:1.10.9.RELEASE

2.2 pom依赖

<?xml version="1.0" encoding="UTF-8"?><project xmlns="http://maven.apache.org/POM/4.0.0"         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">    <parent>        <artifactId>study-parent</artifactId>        <groupId>com.niuniu</groupId>        <version>0.0.1-SNAPSHOT</version>    </parent>    <modelVersion>4.0.0</modelVersion>    <artifactId>demo-mongodb-spring-xml</artifactId>    <properties>        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>        <log4j.version>1.2.16</log4j.version>        <org.slf4j.version>1.7.1</org.slf4j.version>        <junit.version>4.12</junit.version>        <org.springframework.version>4.3.13.RELEASE</org.springframework.version>        <spring-data-mongodb.version>1.10.9.RELEASE</spring-data-mongodb.version>    </properties>    <dependencies>        <dependency>            <groupId>junit</groupId>            <artifactId>junit</artifactId>            <version>${junit.version}</version>            <scope>test</scope>        </dependency>        <dependency>            <groupId>org.slf4j</groupId>            <artifactId>slf4j-jdk14</artifactId>            <version>${org.slf4j.version}</version>        </dependency>        <dependency>            <groupId>log4j</groupId>            <artifactId>log4j</artifactId>            <version>${log4j.version}</version>        </dependency>        <!-- spring framework -->        <dependency>            <groupId>org.springframework</groupId>            <artifactId>spring-context-support</artifactId>            <version>${org.springframework.version}</version>        </dependency>        <dependency>            <groupId>org.springframework</groupId>            <artifactId>spring-beans</artifactId>            <version>${org.springframework.version}</version>        </dependency>        <dependency>            <groupId>org.springframework</groupId>            <artifactId>spring-context</artifactId>            <version>${org.springframework.version}</version>        </dependency>        <dependency>            <groupId>org.springframework</groupId>            <artifactId>spring-core</artifactId>            <version>${org.springframework.version}</version>        </dependency>        <dependency>            <groupId>org.springframework</groupId>            <artifactId>spring-test</artifactId>            <version>${org.springframework.version}</version>            <scope>test</scope>        </dependency>        <dependency>            <groupId>org.springframework.data</groupId>            <artifactId>spring-data-mongodb</artifactId>            <version>${spring-data-mongodb.version}</version>        </dependency>        <dependency>            <groupId>org.projectlombok</groupId>            <artifactId>lombok</artifactId>            <version>1.16.18</version>            <scope>provided</scope>        </dependency>    </dependencies>    <build>        <plugins>            <plugin>                <artifactId>maven-compiler-plugin</artifactId>                <version>2.3.2</version>                <configuration>                    <source>1.8</source>                    <target>1.8</target>                    <encoding>UTF-8</encoding>                </configuration>            </plugin>        </plugins>    </build></project>

3 xml配置

3.1 配置属性文件mongodb.properties

mongodb.dbname=test1mongodb.host=172.19.58.12mongodb.port=27018#mongodb.username=root#mongodb.password=rootmongodb.connectionsPerHost=8mongodb.threadsAllowedToBlockForConnectionMultiplier=4mongodb.connectTimeout=1500mongodb.maxWaitTime=1500mongodb.autoConnectRetry=truemongodb.socketKeepAlive= truemongodb.socketTimeout=1500mongodb.slaveOk=truemongodb.writeNumber=1mongodb.writeTimeout=0mongodb.writeFsync=true

3.2 配置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-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/beans          http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">    <context:property-placeholder location="classpath:mongodb.properties"/>    <context:component-scan base-package="com.niuniu.study.data.*" />    <mongo:mongo host="${mongodb.host}" port="${mongodb.port}">        <mongo:options connections-per-host="${mongodb.connectionsPerHost}"                       threads-allowed-to-block-for-connection-multiplier="${mongodb.threadsAllowedToBlockForConnectionMultiplier}"                       connect-timeout="${mongodb.connectTimeout}"                       max-wait-time="${mongodb.maxWaitTime}"                       auto-connect-retry="${mongodb.autoConnectRetry}"                       socket-keep-alive="${mongodb.socketKeepAlive}"                       socket-timeout="${mongodb.socketTimeout}"                       slave-ok="${mongodb.slaveOk}"                       write-number="${mongodb.writeNumber}"                       write-timeout="${mongodb.writeTimeout}"                       write-fsync="${mongodb.writeFsync}"/>    </mongo:mongo>    <mongo:db-factory dbname="${mongodb.dbname}" mongo-ref="mongo"/>    <bean id="mongoTemplate" class="org.springframework.data.mongodb.core.MongoTemplate">        <constructor-arg name="mongoDbFactory" ref="mongoDbFactory"/>    </bean></beans>

分片配置如下:

<mongo:mongo id="replicaSetMongo" replica-set="127.0.0.1:27017,localhost:27018"/>

4 封装dao

4.1 基本接口类

package com.niuniu.study.data.dao.base.mongodb;import org.springframework.data.mongodb.core.query.Query;import org.springframework.data.mongodb.core.query.Update;import java.util.List;/** * @author 002991 */public interface BaseMongoDao<T> {    /**     * 插入     * @param entity     */    void insert(T entity);    /**     * 查找一个     * @param id     * @return     */    T findOne(String id);    /**     * 按条件查找     * @param query     * @return     */    List<T> find(Query query);    /**     * 统计查找结果个数     * @param query     * @return     */    Long findCount(Query query);    /**     * 分页查-按照创建时间升序排列     * @param skip     * @param limit     * @param query     * @return     */    List<T> findList(Integer skip, Integer limit, Query query);    /**     * 查找并更新第一个     * @param query     * @param update     * @return     * @throws Exception     */    Integer update(Query query, Update update) throws Exception;    /**     * 按照主键更新第一个     * @param entity     * @return     * @throws Exception     */    Integer update(T entity) throws Exception;    /**     * 根据主键删除     * @param entity     * @return     */    Integer remove(T entity);    /**     * 根据条件删除给定表中的文档     * @param query     * @param entity     * @return     */    Integer remove(Query query, T entity);}

4.2 基本接口实现类

package com.niuniu.study.data.dao.base.mongodb;import com.mongodb.WriteResult;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.data.domain.Sort;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.springframework.data.mongodb.core.query.Update;import java.lang.reflect.ParameterizedType;import java.util.List;import java.util.Map;/** * @author 002991 */public class BaseMongoDaoImpl<T> implements BaseMongoDao<T> {    private Class<T> clazz;    @Autowired    private MongoTemplate mongoTemplate;    @Autowired    private MongoUtil mongoUtil;    public BaseMongoDaoImpl() {        ParameterizedType parameterizedType = (ParameterizedType) getClass().getGenericSuperclass();        clazz = (Class<T>) parameterizedType.getActualTypeArguments()[0];    }    @Override    public void insert(T entity) {        mongoTemplate.insert(entity);    }    @Override    public T findOne(String id) {        Query query = new Query();        query.addCriteria(new Criteria("_id").is(id));        return getMongoTemplate().findOne(query,clazz);    }    @Override    public List<T> find(Query query) {        return getMongoTemplate().find(query,clazz);    }    @Override    public Long findCount(Query query) {        return getMongoTemplate().count(query,clazz);    }    @Override    public List<T> findList(Integer skip, Integer limit,Query query) {        query.with(new Sort(new Sort.Order(Sort.Direction.ASC,"createTime")));        query.skip(skip).limit(limit);        return find(query);    }    @Override    public Integer update(Query query, Update update) throws Exception {        WriteResult writeResult = getMongoTemplate().updateFirst(query,update,clazz);        return (null == writeResult ? 0 : writeResult.getN());    }    @Override    public Integer update(T entity) throws Exception {        Map<String,Object> map = mongoUtil.converObjectToParams(entity);        Query query = new Query();        query.addCriteria(new Criteria("_id").is(map.get("id")));        Update update = (Update) map.get("update");        return this.update(query,update);    }    @Override    public Integer remove(T entity) {        WriteResult writeResult = getMongoTemplate().remove(entity);        return (null == writeResult ? 0 : writeResult.getN());    }    @Override    public Integer remove(Query query, T entity) {        WriteResult writeResult = getMongoTemplate().remove(query,entity.getClass());        return (null == writeResult ? 0 : writeResult.getN());    }    public MongoTemplate getMongoTemplate(){        return mongoTemplate;    }}

4.3 工具类

package com.niuniu.study.data.dao.base.mongodb;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.data.mongodb.core.query.Update;import org.springframework.stereotype.Component;import java.util.HashMap;import java.util.Iterator;import java.util.Map;import java.util.Set;/** * @author 002991 */@Componentpublic class MongoUtil {    @Autowired    private MongoObjectParams objectParams;    public Map<String,Object> converObjectToParams(Object object) throws Exception {        Map<String,Object> map = new HashMap<>(16);        Update update = new Update();        Map<String,Object> params = objectParams.createParams(object);        String id = (String) params.get("id");        Set<Map.Entry<String,Object>> sets = params.entrySet();        Iterator<Map.Entry<String,Object>> iteratos = sets.iterator();        while(iteratos.hasNext()){            Map.Entry<String,Object> entry = iteratos.next();            String key = entry.getKey();            Object value = entry.getValue();            if(!key.equals("id")){                update.set(key,value);            }        }        map.put("id",id);        map.put("update",update);        return map;    }}

4.4 参数辅助类

package com.niuniu.study.data.dao.base.mongodb;import org.springframework.stereotype.Component;import java.lang.reflect.Field;import java.util.HashMap;import java.util.Map;/** * @author 002991 */@Componentpublic class MongoObjectParams {    private  String javaType = "java";    /**     * 获取查询的参数     *     * @param object     * @return     * @throws Exception     */    public  Map<String, Object> createParams(Object object) throws Exception {        Map<String, Object> params = new HashMap<>(16);        setIntoParams(params,object, null);        return params;    }    private  void setIntoParams(Map<String, Object> params,Object object, String fatherName) throws IllegalAccessException,            Exception {        Field[] fields = object.getClass().getDeclaredFields();        for (Field file : fields) {            boolean accessFlag = file.isAccessible();            file.setAccessible(true);            String name = file.getName();            Object value = file.get(object);            if(file.getType().getName().equals("java.lang.Class")){                break;            }else if(file.getType().getName().contains(javaType)){                if(fatherName != null && !fatherName.equals(" ")){                    name = fatherName+"."+name;                }                if(value != null){                    params.put(name, value);                }            }else{                if(value != null){                    setIntoParams(params,file.get(object), name);                }            }            file.setAccessible(accessFlag);        }    }}

5 测试

5.1 测试bean

package com.niuniu.study.data.bean;import lombok.Data;import java.io.Serializable;/** * @author 002991 */@Datapublic class UserBean implements Serializable {    private static final long serialVersionUID = 1L;    private String userName;    private String password;    public UserBean() {}    public UserBean(String userName, String password) {        super();        this.userName = userName;        this.password = password;    }}

5.2 测试接口

package com.niuniu.study.data.dao;import com.niuniu.study.data.bean.UserBean;import com.niuniu.study.data.dao.base.mongodb.BaseMongoDao;/** * @author 002991 */public interface UserDao extends BaseMongoDao<UserBean> {}

5.3 测试实现类

package com.niuniu.study.data.dao.mongodb;import com.niuniu.study.data.bean.UserBean;import com.niuniu.study.data.dao.UserDao;import com.niuniu.study.data.dao.base.mongodb.BaseMongoDaoImpl;import org.springframework.stereotype.Repository;/** * @author 002991 */@Repositorypublic class UserDaoImpl extends BaseMongoDaoImpl<UserBean> implements UserDao {}

5.4 测试类

package com.niuniu.study.data;import com.niuniu.study.data.bean.UserBean;import com.niuniu.study.data.dao.UserDao;import org.junit.Test;import org.junit.runner.RunWith;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.data.mongodb.core.query.Criteria;import org.springframework.data.mongodb.core.query.Query;import org.springframework.test.context.ContextConfiguration;import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;import java.util.List;@RunWith(SpringJUnit4ClassRunner.class)@ContextConfiguration(locations = {"classpath:spring-mongodb.xml"})public class MongodbTest {    @Autowired    private UserDao userDao;    /**     * 根据主键获取实体     */    @Test    public void testFindOne(){        UserBean userBean = userDao.findOne("593e3f8ba4977227581b398c");        System.out.println(userBean);    }    /**     * 根据过滤条件获取集合列表     */    @Test    public void testFind(){        Query query = new Query();        List<UserBean> list1 = userDao.find(query);        System.out.println(list1.size());        query = new Query();        query.addCriteria(new Criteria("InterfaceMethod").nin("InterfaceMethod5"));        List<UserBean> list2 = userDao.find(query);        for(UserBean userBean : list2){            System.out.println(userBean);        }    }    /**     * 根据过滤条件获取查询个数     */    @Test    public void testFindCount(){        Query query = new Query();        query.addCriteria(new Criteria("InterfaceMethod").nin("InterfaceMethod5"));        System.out.println(userDao.findCount(query));    }    /**     * 根据过滤条件获取分页集合     * skip:从第几条开始,但不包括这条数据     * limit:每页几条数据     */    @Test    public void testFindList(){        Query query = new Query();        query.addCriteria(new Criteria("InterfaceMethod").nin("InterfaceMethod11"));        List<UserBean> list = userDao.findList(10,5,query);        for(UserBean userBean : list){            System.out.println(userBean.getUserName());        }    }    /**     * 实体新增     */    @Test    public void testInsert(){        for(int i = 0; i < 30 ; i++){            UserBean userBean = new UserBean("username" + i,"password" + i);            userDao.insert(userBean);        }    }    /**     * 通过传入的实体ID更新实体中的其他内容     * @throws Exception     */    @Test    public void testUpdate() throws Exception{        UserBean userBean = userDao.findOne("593e3f8ba4977227581b398c");        System.out.println("1------------->" + userBean.getUserName());        userBean.setUserName("setBusinessNametest");        userDao.update(userBean);        userBean = userDao.findOne("593e3f8ba4977227581b398c");        System.out.println("2------------->" + userBean.getUserName());    }    /**     * 删除实体对象     */    @Test    public void testRemove(){        UserBean userBean = userDao.findOne("593e4f1ca4977223d8f705aa");        System.out.println(userBean);        userDao.remove(userBean);        userBean = userDao.findOne("593e4f1ca4977223d8f705aa");        System.out.println(userBean);    }    /**     * 通过过滤条件和实体对象删除对应数据     */    @Test    public void testRemoveByQuery(){        Query query = new Query();        query.addCriteria(new Criteria("_id").is("593e4f1ca4977223d8f705a3"));        UserBean entity = new UserBean();        System.out.println(userDao.remove(query,entity));    }}

6 源码地址

本文源代码地址:https://gitee.com/once999/study-parent/tree/master/demo-mongodb-spring-xml

最新文章

123

最新摄影

闪念基因

微信扫一扫

第七城市微信公众平台