javaWeb項目中集成MongoDB-3.x數據庫

1、說明

1.能夠知道的是mongodb2.x和3.x置是不一樣的。java

2.這裏只說明須要權限驗證的配置web

3.最好spring 4.2.6以上吧(反正我這樣完成的配置測試修改 須要4.2.6版本)+MongoDB 3.2.13 其餘的版本不清楚。spring

4.具體jar 很少說 版本如圖 驅動3.2.1 ----spring支持mongodb 包1.10mongodb

輸入圖片說明

2、配置

1.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:mongo="http://www.springframework.org/schema/data/mongo"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/data/mongo http://www.springframework.org/schema/data/mongo/spring-mongo-1.10.xsd http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd"> 
        <!-- 定義mongo對象,對應的是mongodb官方jar包中的Mongo, --> <!-- MongoClient -->
    <bean id="mongoClient" class="com.mongodb.MongoClient">
        <constructor-arg name="credentialsList">
            <list> 
            <!-- Credentials -->
                <bean class="com.mongodb.MongoCredential">
                    <constructor-arg name="mechanism" value="#{T(com.mongodb.AuthenticationMechanism).SCRAM_SHA_1}"/>
                    <constructor-arg type="java.lang.String" name="userName" value="xxxx"/>
                    <constructor-arg type="java.lang.String" name="source" value="xxxx"/>
                    <constructor-arg type="char[]" name="password" value="xxxx"/>
                </bean>
            </list>
        </constructor-arg>
        <constructor-arg name="seeds">
            <list>
                <bean class="com.mongodb.ServerAddress">
                    <constructor-arg type="java.lang.String" name="host" value="127.0.0.1"/>
                    <constructor-arg type="int" name="port" value="27017"/>
                </bean>
<!--                 <bean class="com.mongodb.ServerAddress"> -->
<!--                     <constructor-arg type="java.lang.String" name="host" value="${mongo.sharded_clusters2.host}"/> -->
<!--                     <constructor-arg type="int" name="port" value="${mongo.sharded_clusters2.port}"/> -->
<!--                 </bean> -->
<!--                 <bean class="com.mongodb.ServerAddress"> -->
<!--                     <constructor-arg type="java.lang.String" name="host" value="${mongo.sharded_clusters2.host}"/> -->
<!--                     <constructor-arg type="int" name="port" value="${mongo.sharded_clusters3.port}"/> -->
<!--                 </bean> -->
            </list>
        </constructor-arg>
    </bean> <!-- MongoDbFactory -->
    <bean id="simpleMongoDbFactoryID" class="org.springframework.data.mongodb.core.SimpleMongoDbFactory">
        <constructor-arg ref="mongoClient"/>
        <constructor-arg name="databaseName" value="xxxx"/>
    </bean> <!-- MongoTemplate -->
    <bean id="mongoTemplate" class="org.springframework.data.mongodb.core.MongoTemplate">
        <constructor-arg ref="simpleMongoDbFactoryID"/>
    </bean>
</beans>

還查到一種配置express

<?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"
       xmlns:aop="http://www.springframework.org/schema/aop"
       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.xsd
          http://www.springframework.org/schema/aop 
          http://www.springframework.org/schema/aop/spring-aop-3.0.xsd  
          http://www.springframework.org/schema/beans   
          http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
          http://www.springframework.org/schema/data/repository
http://www.springframework.org/schema/data/repository/spring-repository-1.5.xsd">

    <!-- 加載mongodb的屬性配置文件 -->
<!--     <context:property-placeholder location="classpath:mongo.properties" /> -->

    <!-- 定義mongo對象,對應的是mongodb官方jar包中的Mongo,replica-set設置集羣副本的ip地址和端口 -->
<!--     
    <mongo:mongo id="mongo" host="${mongo.host}" port="${mongo.port}" >
    
    <mongo:client-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> 
    -->
<!--    咱們使用的mongodb的版本是3.X,因此在構造這段話的時候要根據 Mongo類的構造函數來構造,不一樣版本可能會形成構造函數的不一樣 -->
    <mongo:mongo-client id="mongo" host="127.0.0.1" port="27017" credentials="chen:chen@patient">
    
        <mongo:client-options 
        connections-per-host="8" 
        threads-allowed-to-block-for-connection-multiplier="4" 
        connect-timeout=" 1500" 
        max-wait-time=" 1500" 
        socket-keep-alive="true" 
        socket-timeout=" 1500"        
       /> 
    </mongo:mongo-client>

    <!-- 用戶驗證 -->
    <bean id="userCredentials" class="org.springframework.data.authentication.UserCredentials">
        <constructor-arg name="username" value="chen" />
        <constructor-arg name="password" value="chen" />
    </bean>
    <!-- mongo的工廠,經過它來取得mongo實例,dbname爲mongodb的數據庫名,沒有的話會自動建立 -->
    <bean id="mongoDbFactory"
        class="org.springframework.data.mongodb.core.SimpleMongoDbFactory">
        <constructor-arg ref="mongo" />
        <constructor-arg value="patient" />
        <!-- <constructor-arg ref="userCredentials" /> -->
    </bean>

    <bean id="mappingContext"
        class="org.springframework.data.mongodb.core.mapping.MongoMappingContext" />

    <bean id="defaultMongoTypeMapper"
        class="org.springframework.data.mongodb.core.convert.DefaultMongoTypeMapper">
        <constructor-arg name="typeKey">
            <null />
        </constructor-arg>
    </bean>

    <!-- collection的映射 -->
    <bean id="mappingMongoConverter"
        class="org.springframework.data.mongodb.core.convert.MappingMongoConverter">
        <constructor-arg name="mongoDbFactory" ref="mongoDbFactory" />
        <constructor-arg name="mappingContext" ref="mappingContext" />
        <property name="typeMapper" ref="defaultMongoTypeMapper" />
    </bean>

    <!-- mongodb的主要操做對象,全部對mongodb的增刪改查的操做都是經過它完成 -->
    <bean id="mongoTemplate" class="org.springframework.data.mongodb.core.MongoTemplate">
        <constructor-arg name="mongoDbFactory" ref="mongoDbFactory" />
        <constructor-arg name="mongoConverter" ref="mappingMongoConverter" />
    </bean>
<!--     <bean id="dao" class="com.wanliyun.mongoDao.daoImp"/> -->
<!--     mongodb事務 -->
<!--     <bean id="audience" class="cn.com.bluemoon.mongodb.aop.Audience"/> -->

<!--     <aop:config proxy-target-class="true"> -->
<!--         <aop:aspect ref="audience"> -->
<!--             <aop:pointcut id="performance" expression="execution(* cn.com.mongodb.service.impl.*.*(..))"/> -->
            
<!--             <aop:before pointcut-ref="performance" method="takeSeats"/> -->
<!--             <aop:before pointcut-ref="performance" method="turnOffCellPhones"/> -->
<!--             <aop:around pointcut-ref="performance" method="around"/> -->
<!--             <aop:after-returning pointcut-ref="performance" method="applaud"/> -->
<!--             <aop:after-throwing pointcut-ref="performance" method="demandRefund"/> -->
<!--             <aop:after pointcut-ref="performance" method="after"/> -->
<!--         </aop:aspect> -->
<!--     </aop:config> -->
</beans>

2.springMVC-context.xmlspring-mvc

<beans xmlns="http://www.springframework.org/schema/beans" xmlns:p="http://www.springframework.org/schema/p" xmlns:context="http://www.springframework.org/schema/context" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:mvc="http://www.springframework.org/schema/mvc" xsi:schemaLocation="http://www.springframework.org/schema/mvc
		http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
        http://www.springframework.org/schema/context 
        http://www.springframework.org/schema/context/spring-context-3.0.xsd
		http://www.springframework.org/schema/beans
		http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
	<!-- 註解掃描包 掃描com.zhcv包以及子包下註解爲 Controller Service Repository Compotent的類 -->
	<context:component-scan base-package="com.xxxx.controller" />
<!-- 管理mongodbDao-->
 	 <context:component-scan base-package="com.xxxx.mongoDao.daoImp"/>
	<!-- 開啓註解 -->
	<mvc:annotation-driven />
	<!-- 定義視圖解析器, "/" 默認放在WebRoot下 -->
	<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
		<property name="viewClass" value="org.springframework.web.servlet.view.JstlView" />
		<property name="prefix" value="/page/" />
		<property name="suffix" value=".jsp"></property>
	</bean>
	<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
		<property name="maxUploadSize" value="10485760" />
	</bean>
	  <!-- 加載mongodb配置-->
	<import resource="spring-mongodb.xml" />
</beans>

3、java 工具類+流程代碼

1.mongodb操做模板MongoTemplate 在服務啓動,spring-mongodb.xml加載時加載模板mvc

package com.xxxx.mongoDao.daoImp;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.data.mongodb.core.MongoTemplate;

public abstract class AbstractBaseMongoTemplete implements ApplicationContextAware {

	protected MongoTemplate mongoTemplate;

	/**
	 * @Description 根據配置文件設置mongoTemplate
	 * @param mongoTemplate
	 */
	public void setMongoTemplate(MongoTemplate mongoTemplate) {
		this.mongoTemplate = mongoTemplate;
	}

	@Override
	public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
		MongoTemplate mongoTemplate = applicationContext.getBean("mongoTemplate", MongoTemplate.class);
		setMongoTemplate(mongoTemplate);
		System.out.println("mongoTemplate===" + mongoTemplate);
	}
}

2.java實體--對應---Mongodb 中collection(table/集合)app

import java.io.Serializable;

public class UserModel implements Serializable {

	private static final long serialVersionUID = 1L;
	private String name;
	private int age;

	public UserModel(String name, int age) {
		super();
		this.name = name;
		this.age = age;
	}

	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;
	}

	@Override
	public String toString() {
		return "UserModel [name=" + name + ", age=" + age + "]";
	}

}

3.Dao層接口UserDaosocket

import java.util.List;

import com.mongodb.BasicDBList;
import com.mongodb.DBObject;


public interface UserDao {
	/**
	 * 查詢全部
	 * 
	 * @author lennon
	 * @return
	 * @time 2017-5-24 下午4:18:55
	 * @version
	 */
	public List<UserModel> findAll();

	/**
	 * 新增數據
	 * 
	 * @author lennon
	 * @param user
	 * @time 2017-5-24 下午4:19:08
	 * @version
	 */
	public void insertUser(UserModel user);

	/**
	 * 刪除數據
	 * 
	 * @author lennon
	 * @param userName
	 * @time 2017-5-24 下午4:19:17
	 * @version
	 */
	public void removeUser(String userName);

	/**
	 * 修改數據
	 * 
	 * @author lennon
	 * @param user
	 * @time 2017-5-24 下午4:19:25
	 * @version
	 */
	public void updateUser(UserModel user);

	/**
	 * 按條件查詢
	 * 
	 * @author lennon
	 * @param userName
	 * @return
	 * @time 2017-5-24 下午4:19:32
	 * @version
	 */
	public List<UserModel> findForRequery(String userName);

	/**
	 * mongodb簡單的分組查詢
	 * 
	 * @author lennon
	 * @return
	 * @time 2017-5-24 下午4:19:41
	 * @version
	 */
	public BasicDBList mongoGroup();

	public void saveData(DBObject obj);

}

接口實現類UserDaoImp** 注意(註解),具體實現還有待完善,也沒有徹底明白**

@Component("UserDaoImp")
public class UserDaoImp extends AbstractBaseMongoTemplete implements UserDao {

	@Override
	public List<UserModel> findAll() {
		// 須要設置集合對應的屍體類和相應的集合名,從而查詢結果直接映射
		System.out.println("mongoTemplate==" + mongoTemplate);
		List<UserModel> userList = mongoTemplate.findAll(UserModel.class, "user");
		return userList;
	}

	@Override
	public void insertUser(UserModel user) {
		// 設置須要插入到數據庫的文檔對象
		DBObject object = new BasicDBObject();
		object.put("name", user.getName());
		object.put("age", user.getAge());
		mongoTemplate.insert(object, "user");
	}

	@Override
	public void removeUser(String userName) {
		// 設置刪除條件,若是條件內容爲空則刪除全部
		Query query = new Query();
		Criteria criteria = new Criteria("name");
		criteria.is(userName);
		query.addCriteria(criteria);
		mongoTemplate.remove(query, "user");
	}

	@Override
	public void updateUser(UserModel user) {
		// 設置修改條件
		Query query = new Query();
		Criteria criteria = new Criteria("name");
		criteria.is(user.getName());
		query.addCriteria(criteria);
		// 設置修改內容
		Update update = Update.update("age", user.getAge());
		// 參數:查詢條件,更改結果,集合名
		mongoTemplate.updateFirst(query, update, "user");
	}

	@Override
	public List<UserModel> findForRequery(String userName) {
		Query query = new Query();
		Criteria criteria = new Criteria("name");
		criteria.regex(".*?" + "a" + ".*");
		// criteria.is(userName);
		// Pattern pattern = Pattern.compile("^.*a.*$",
		// Pattern.CASE_INSENSITIVE);
		// DBObject object = new BasicDBObject();
		// object.put("name", pattern);
		// criteria.is(object);
		// criteria.
		// query.addCriteria(criteria);
		// mongoTemplate.find(new Query(new Criteria(
		// "name").regex(".*?"+"張"+".*")).limit(9), User.class);
		// 查詢條件,集合對應的實體類,集合名
		query.addCriteria(criteria);
		List<UserModel> userList = mongoTemplate.find(query, UserModel.class, userName);
		return userList;
	}

	@Override
	public BasicDBList mongoGroup() {
		// TODO Auto-generated method stub
		GroupBy groupBy = GroupBy.key("age").initialDocument("{count:0}").reduceFunction("function(doc, out){out.count++}").finalizeFunction("function(out){return out;}");
		GroupByResults<UserModel> res = mongoTemplate.group("test", groupBy, UserModel.class);
		DBObject obj = res.getRawResults();
		BasicDBList dbList = (BasicDBList) obj.get("retval");
		return dbList;
	}

	@Override
	public void saveData(DBObject obj) {
		mongoTemplate.save(obj, "test");
	}

}

4.controller 實現調用

/**
 * @author lennon
 * 
 */
@Controller
public class MongoDb {
	@Autowired
	private UserDao userDao;
	
	@RequestMapping(value = "setMongo")
	public void setMongo(HttpServletRequest request, HttpServletResponse response) {
		// userDao.findAll();
		UserModel user = new UserModel("皇帝1", 10000);
		
		userDao.insertUser(user);
	}
}

該例子只實現了 編譯運行 簡單操做沒問題 作到對使用mongodb的瞭解,之後還要慢慢深刻

相關文章
相關標籤/搜索