1. 程式人生 > >ssm(spring+springMVC+Mybatis)框架整合Mongodb

ssm(spring+springMVC+Mybatis)框架整合Mongodb

1、開發環境

JDK:1.6

ssm框架關聯jar包:

aopalliance.jar
aspectjrt.jar
aspectjweaver.jar
commons-beanutils-1.9.2.jar
commons-codec-1.9.jar
commons-collections-3.2.1.jar
commons-dbcp-1.4.jar
commons-fileupload-1.3.1.jar
commons-io-2.4.jar
commons-lang-2.6.jar
commons-logging-1.2.jar
commons-net-3.1.jar
commons-pool-1.6.jar
commons-pool2-2.2.jar
druid-1.0.9.jar
fastjson-1.1.39.jar
freemarker-2.3.19.jar
hamcrest-core-1.3.jar
jackson-all-1.9.5.jar
jboss-logging-3.1.0.CR2.jar
jettison-1.0.1.jar
jstl-1.1.2.jar
junit-4.11.jar
log4j-1.2.17.jar
log4j-over-slf4j-1.7.7.jar
mybatis-3.2.6.jar
mybatis-spring-1.2.2.jar
mysql-connector-java-5.1.30-bin.jar
servlet-api.jar
slf4j-api-1.7.7.jar
slf4j-ext-1.7.7.jar
spring-aop-4.0.2.RELEASE.jar
spring-aspects-4.0.2.RELEASE.jar
spring-beans-4.0.2.RELEASE.jar
spring-context-4.0.2.RELEASE.jar
spring-context-support-4.0.2.RELEASE.jar
spring-core-4.0.2.RELEASE.jar
spring-expression-4.0.2.RELEASE.jar
spring-jdbc-4.0.2.RELEASE.jar
spring-oxm-4.0.2.RELEASE.jar
spring-test-4.0.2.RELEASE.jar
spring-tx-4.0.2.RELEASE.jar
spring-web-4.0.4.RELEASE.jar
spring-webmvc-4.0.2.RELEASE.jar
standard-1.1.2.jar

mongodb 關聯jar檔案
mongo-java-driver-2.10.1.jar
spring-data-commons-core-1.4.0.RELEASE.jar
spring-data-mongodb-1.1.0.RELEASE.jar


專案結構圖:

2、配置檔案和實列程式碼

web.xml檔案

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" 
	xmlns="http://java.sun.com/xml/ns/javaee" 
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
	xsi:schemaLocation="http://java.sun.com/xml/ns/javaee 
	http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
  <display-name></display-name>	
  
  <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:spring/spring-context.xml</param-value>
    </context-param>
 
    <filter>
        <filter-name>encodingFilter</filter-name>
        <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
        <init-param>
            <param-name>encoding</param-name>
            <param-value>UTF-8</param-value>
        </init-param>
        <init-param>
            <param-name>forceEncoding</param-name>
            <param-value>true</param-value>
        </init-param>
    </filter>
    <filter-mapping>
        <filter-name>encodingFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
 
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>
 
    <servlet>
        <servlet-name>springMVC</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:spring-mvc.xml</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>springMVC</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>
  

</web-app>

spring-mvc.xml

<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:p="http://www.springframework.org/schema/p"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:mvc="http://www.springframework.org/schema/mvc"
       xsi:schemaLocation="
       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
       http://www.springframework.org/schema/mvc
       http://www.springframework.org/schema/mvc/spring-mvc.xsd">

    

    <!-- 開啟controller註解支援 -->
    <!-- 注意事項請參考:http://jinnianshilongnian.iteye.com/blog/1762632 -->
    <context:component-scan base-package="cn.zetark.oauth2.**.web.controller" use-default-filters="false">
        <context:include-filter type="annotation"
                                expression="org.springframework.stereotype.Controller"/>
        <context:include-filter type="annotation"
                                expression="org.springframework.web.bind.annotation.ControllerAdvice"/>
    </context:component-scan>
	<!--註解標籤驅動  -->
    <mvc:annotation-driven>
    </mvc:annotation-driven>

    <!-- 當在web.xml 中   DispatcherServlet使用 <url-pattern>/</url-pattern> 對映時,能對映靜態資源 -->
    <mvc:default-servlet-handler/>

    <!-- 靜態資源對映 -->
    <mvc:resources mapping="/static/**" location="/WEB-INF/static/"/>

    <!-- 預設的檢視解析器 在上邊的解析錯誤時使用 (預設使用html)- -->
    <bean id="defaultViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver"
          p:order="1">
        <property name="viewClass" value="org.springframework.web.servlet.view.JstlView"/>
        <property name="contentType" value="text/html"/>
        <property name="prefix" value="/WEB-INF/jsp/"/>
        <property name="suffix" value=".jsp"/>
    </bean>
    
    <!--避免IE執行AJAX時,返回JSON出現下載檔案 -->
	<bean id="mappingJacksonHttpMessageConverter"
		class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter">
		<property name="supportedMediaTypes">
			<list>
				<value>text/html;charset=UTF-8</value>
			</list>
		</property>
	</bean>
	<!-- 啟動SpringMVC的註解功能,完成請求和註解POJO的對映 -->
	<bean
		class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
		<property name="messageConverters">
			<list>
				<ref bean="mappingJacksonHttpMessageConverter" />	<!-- JSON轉換器 -->
			</list>
		</property>
	</bean>

   

  

</beans>

spring-context.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:p="http://www.springframework.org/schema/p"
	xmlns:context="http://www.springframework.org/schema/context"
	xmlns:mvc="http://www.springframework.org/schema/mvc"
	xmlns:tx="http://www.springframework.org/schema/tx"
	xmlns:aop="http://www.springframework.org/schema/aop"
	xsi:schemaLocation="http://www.springframework.org/schema/beans  
                        http://www.springframework.org/schema/beans/spring-beans-3.1.xsd  
                        http://www.springframework.org/schema/context  
                        http://www.springframework.org/schema/context/spring-context-3.1.xsd  
                        http://www.springframework.org/schema/tx
                        http://www.springframework.org/schema/tx/spring-tx-3.1.xsd
                        http://www.springframework.org/schema/mvc  
                        http://www.springframework.org/schema/mvc/spring-mvc-3.1.xsd
                        http://www.springframework.org/schema/aop 
                        http://www.springframework.org/schema/aop/spring-aop-3.1.xsd">   
	<!-- 引入配置檔案 -->
	<bean id="propertyConfigurer"
		class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
		<property name="location" value="classpath:jdbc.properties" />
	</bean>

	<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
		destroy-method="close">
		<property name="driverClassName" value="${driver}" />
		<property name="url" value="${url}" />
		<property name="username" value="${username}" />
		<property name="password" value="${password}" />
		<!-- 初始化連線大小 -->
		<property name="initialSize" value="${initialSize}"></property>
		<!-- 連線池最大數量 -->
		<property name="maxActive" value="${maxActive}"></property>
		<!-- 連線池最大空閒 -->
		<property name="maxIdle" value="${maxIdle}"></property>
		<!-- 連線池最小空閒 -->
		<property name="minIdle" value="${minIdle}"></property>
		<!-- 獲取連線最大等待時間 -->
		<property name="maxWait" value="${maxWait}"></property>
	</bean>

	<!-- spring和MyBatis完美整合,不需要mybatis的配置對映檔案 -->
	<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
		<property name="dataSource" ref="dataSource" />
		<!-- 自動掃描mapping.xml檔案 -->
		<property name="mapperLocations" value="classpath:com/wlsq/oauth/mapper/*.xml"></property>
	</bean>

	<!-- DAO介面所在包名,Spring會自動查詢其下的類 -->
	<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
		<property name="basePackage" value="com.wlsq.oauth.dao" />
		<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"></property>
	</bean>

	<!-- (事務管理)transaction manager, use JtaTransactionManager for global tx -->
	<bean id="transactionManager"
		class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
		<property name="dataSource" ref="dataSource" />
	</bean>
	
	 <!-- 通知 -->
    <tx:advice id="tx"
        transaction-manager="transactionManager">
        <tx:attributes>
            <tx:method name="delete*" propagation="REQUIRED" />
            <tx:method name="insert*" propagation="REQUIRED" />
            <tx:method name="update*" propagation="REQUIRED" />
            <tx:method name="find*" read-only="true" />
            <tx:method name="get*" read-only="true" />
            <tx:method name="select*" read-only="true" />
        </tx:attributes>
    </tx:advice>

    <aop:config>
        <aop:pointcut id="pc" expression="execution(* com.common.service.*.*(..))" />
        <!--把事務控制在Service層-->
        <aop:advisor pointcut-ref="pc" advice-ref="tx" />
    </aop:config>
    
    <!--ssm 整合 mongodb  -->
    <import resource="classpath:spring/spring-mongodb.xml"/>

</beans>

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:p="http://www.springframework.org/schema/p"   
    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/data/mongo  
            http://www.springframework.org/schema/data/mongo/spring-mongo.xsd
            http://www.springframework.org/schema/data/repository
            http://www.springframework.org/schema/data/repository/spring-repository-1.4.xsd ">  
                  
    <!-- Default bean name is 'mongo' -->  
    <mongo:mongo host="120.25.56.93" port="27017"/>  
      
    <!--mongodb 資料庫賬號和密碼資訊  -->
 
    <bean id="userCredentials" class="org.springframework.data.authentication.UserCredentials">
		<constructor-arg name="username"  value="admin"/>
		<constructor-arg name="password"  value="123456"/>
	</bean> 
    
    <!-- Offers convenience methods and automatic mapping between MongoDB JSON documents and your domain classes. -->  
    <bean id="mongoTemplate" class="org.springframework.data.mongodb.core.MongoTemplate">  
            <constructor-arg ref="mongo"/>  
            <constructor-arg name="databaseName" value="admin"/>  
            <constructor-arg ref="userCredentials"/> 
    </bean>  
    
    <bean id="userDao" class="com.wlsq.oauth.dao.impl.UserDao" />
      
</beans>

mongodb 邏輯封裝程式碼(mongodbTemplate 封裝)
package com.wlsq.oauth.dao.support;

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

public class AbstractBaseMongoTemplete implements ApplicationContextAware {
	protected MongoTemplate mongoTemplate;
	
	/**
	 * 設定mongoTemplate
	 * @param mongoTemplate the mongoTemplate to set
	 */
	public void setMongoTemplate(MongoTemplate mongoTemplate) {
		this.mongoTemplate = mongoTemplate;
	}
	
	public void setApplicationContext(ApplicationContext applicationContext)
			throws BeansException {
		// TODO Auto-generated method stub
		MongoTemplate mongoTemplate = applicationContext.getBean("mongoTemplate", MongoTemplate.class);
		setMongoTemplate(mongoTemplate);
	}

}

mongodb  dao層資料庫介面基類
package com.wlsq.oauth.dao.impl;

import java.util.List;

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 com.wlsq.oauth.dao.IUserDao;
import com.wlsq.oauth.dao.support.AbstractBaseMongoTemplete;
import com.wlsq.oauth.entity.User;

public class UserDao extends AbstractBaseMongoTemplete implements IUserDao {
	/**
	 * 新增
	 * <br>------------------------------<br>
	 * @param user
	 */ 
	public void insert(User user) {
		// TODO Auto-generated method stub
		mongoTemplate.insert(user);
	}
	/**
	 * 批量新增
	 * <br>------------------------------<br>
	 * @param users
	 */
	public void insertAll(List<User> users) {
		// TODO Auto-generated method stub
		mongoTemplate.insertAll(users);
	}
	/**
	 * 刪除,按主鍵id, 如果主鍵的值為null,刪除會失敗
	 * <br>------------------------------<br>
	 * @param id
	 */
	public void deleteById(String id) {
		// TODO Auto-generated method stub
		User user = new User(id, null, 0);
		mongoTemplate.remove(user);
	}
	/**
	 * 按條件刪除
	 * <br>------------------------------<br>
	 * @param criteriaUser
	 */
	public void delete(User criteriaUser) {
		// TODO Auto-generated method stub
		Criteria criteria = Criteria.where("age").gt(criteriaUser.getAge());;
		Query query = new Query(criteria);
		mongoTemplate.remove(query, User.class);
	}
	/**
	 * 刪除全部
	 * <br>------------------------------<br>
	 */
	public void deleteAll() {
		// TODO Auto-generated method stub
		mongoTemplate.dropCollection(User.class);
	}
	/**
	 * 按主鍵修改,
	 * 如果文件中沒有相關key 會新增 使用$set修改器
	 * <br>------------------------------<br>
	 * @param user
	 */
	public void updateById(User user) {
		// TODO Auto-generated method stub
		Criteria criteria = Criteria.where("id").is(user.getId());
		Query query = new Query(criteria);
		Update update = Update.update("age", user.getAge()).set("name", user.getName());
		mongoTemplate.updateFirst(query, update, User.class);
	}
	/**
	 * 修改多條
	 * <br>------------------------------<br>
	 * @param criteriaUser
	 * @param user
	 */
	public void update(User criteriaUser, User user) {
		// TODO Auto-generated method stub
		Criteria criteria = Criteria.where("age").gt(criteriaUser.getAge());;
		Query query = new Query(criteria);
		Update update = Update.update("name", user.getName()).set("age", user.getAge());
		mongoTemplate.updateMulti(query, update, User.class);
	}
	/**
	 * 根據主鍵查詢
	 * <br>------------------------------<br>
	 * @param id
	 * @return
	 */
	public User findById(String id) {
		// TODO Auto-generated method stub
		return mongoTemplate.findById(id, User.class);
	}
	/**
	 * 查詢全部
	 * <br>------------------------------<br>
	 * @return
	 */
	public List<User> findAll() {
		// TODO Auto-generated method stub
		return mongoTemplate.findAll(User.class);
	}
	/**
	 * 按條件查詢, 分頁
	 * <br>------------------------------<br>
	 * @param criteriaUser
	 * @param skip
	 * @param limit
	 * @return
	 */
	public List<User> find(User criteriaUser, int skip, int limit) {
		// TODO Auto-generated method stub
		Query query = getQuery(criteriaUser);
		query.skip(skip);
		query.limit(limit);
		return mongoTemplate.find(query, User.class);
	}
	/**
	 * 根據條件查詢出來後 再去修改
	 * <br>------------------------------<br>
	 * @param criteriaUser  查詢條件
	 * @param updateUser    修改的值物件
	 * @return
	 */
	public User findAndModify(User criteriaUser, User updateUser) {
		// TODO Auto-generated method stub
		Query query = getQuery(criteriaUser);
		Update update = Update.update("age", updateUser.getAge()).set("name", updateUser.getName());
		return mongoTemplate.findAndModify(query, update, User.class);
	}
	/**
	 * 查詢出來後 刪除
	 * <br>------------------------------<br>
	 * @param criteriaUser
	 * @return
	 */
	public User findAndRemove(User criteriaUser) {
		// TODO Auto-generated method stub
		Query query = getQuery(criteriaUser);
		return mongoTemplate.findAndRemove(query, User.class);
	}
	/**
	 * count
	 * <br>------------------------------<br>
	 * @param criteriaUser
	 * @return
	 */
	public long count(User criteriaUser) {
		// TODO Auto-generated method stub
		Query query = getQuery(criteriaUser);
		return mongoTemplate.count(query, User.class);
	}
	/**
	 *
	 * <br>------------------------------<br>
	 * @param criteriaUser
	 * @return
	 */
	private Query getQuery(User criteriaUser) {
		if (criteriaUser == null) {
			criteriaUser = new User();
		}
		Query query = new Query();
		if (criteriaUser.getId() != null) {
			Criteria criteria = Criteria.where("id").is(criteriaUser.getId());
			query.addCriteria(criteria);
		}
		if (criteriaUser.getAge() > 0) {
			Criteria criteria = Criteria.where("age").gt(criteriaUser.getAge());
			query.addCriteria(criteria);
		}
		if (criteriaUser.getName() != null) {
			Criteria criteria = Criteria.where("name").regex("^" + criteriaUser.getName());
			query.addCriteria(criteria);
		}
		return query;
	}

}

package com.wlsq.oauth.dao;

import java.util.List;

import com.wlsq.oauth.entity.User;

public interface IUserDao {
	/**
	 * 新增
	 * <br>------------------------------<br>
	 * @param user
	 */
	void insert(User user);
	
	/**
	 * 新增
	 * <br>------------------------------<br>
	 * @param users
	 */
	void insertAll(List<User> users);
	
	/**
	 * 刪除,主鍵id, 如果主鍵的值為null,刪除會失敗
	 * <br>------------------------------<br>
	 * @param id
	 */
	void deleteById(String id);
	
	/**
	 * 按條件刪除
	 * <br>------------------------------<br>
	 * @param criteriaUser
	 */
	void delete(User criteriaUser);
	
	/**
	 * 刪除全部
	 * <br>------------------------------<br>
	 */
	void deleteAll();
	
	/**
	 * 修改
	 * <br>------------------------------<br>
	 * @param user
	 */
	void updateById(User user);
	
	/**
	 * 更新多條
	 * <br>------------------------------<br>
	 * @param criteriaUser
	 * @param user
	 */
	void update(User criteriaUser, User user);
	
	/**
	 * 根據主鍵查詢
	 * <br>------------------------------<br>
	 * @param id
	 * @return
	 */
	User findById(String id);
	
	/**
	 * 查詢全部
	 * <br>------------------------------<br>
	 * @return
	 */
	List<User> findAll();
	
	/**
	 * 按條件查詢
	 * <br>------------------------------<br>
	 * @param criteriaUser
	 * @param skip
	 * @param limit
	 * @return
	 */
	List<User> find(User criteriaUser, int skip, int limit);
	
	/**
	 * 根據條件查詢出來後 在去修改
	 * <br>------------------------------<br>
	 * @param criteriaUser  查詢條件
	 * @param updateUser    修改的值物件
	 * @return
	 */
	User findAndModify(User criteriaUser, User updateUser);
	
	/**
	 * 查詢出來後 刪除
	 * <br>------------------------------<br>
	 * @param criteriaUser
	 * @return
	 */
	User findAndRemove(User criteriaUser);
	
	/**
	 * count
	 * <br>------------------------------<br>
	 * @param criteriaUser
	 * @return
	 */
	long count(User criteriaUser);

}

mongodb 實體類
package com.wlsq.oauth.entity;

import java.io.Serializable;

public class User implements Serializable {

	/**
	 * 
	 */
	private static final long serialVersionUID = -2634064977259616340L;
	private String id;	
	private String name;	
	private int age;
	
	public User() {		
	}

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

	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 int getAge() {
		return age;
	}

	public void setAge(int age) {
		this.age = age;
	}
	
	
	
	
	
}