当前位置:   article > 正文

ssm(spring+springMVC+Mybatis)框架集成Mongodb_mybatis 增加 mongodb

mybatis 增加 mongodb

1、开发环境

JDK:1.6

ssm框架关联jar包:

  1. aopalliance.jar
  2. aspectjrt.jar
  3. aspectjweaver.jar
  4. commons-beanutils-1.9.2.jar
  5. commons-codec-1.9.jar
  6. commons-collections-3.2.1.jar
  7. commons-dbcp-1.4.jar
  8. commons-fileupload-1.3.1.jar
  9. commons-io-2.4.jar
  10. commons-lang-2.6.jar
  11. commons-logging-1.2.jar
  12. commons-net-3.1.jar
  13. commons-pool-1.6.jar
  14. commons-pool2-2.2.jar
  15. druid-1.0.9.jar
  16. fastjson-1.1.39.jar
  17. freemarker-2.3.19.jar
  18. hamcrest-core-1.3.jar
  19. jackson-all-1.9.5.jar
  20. jboss-logging-3.1.0.CR2.jar
  21. jettison-1.0.1.jar
  22. jstl-1.1.2.jar
  23. junit-4.11.jar
  24. log4j-1.2.17.jar
  25. log4j-over-slf4j-1.7.7.jar
  26. mybatis-3.2.6.jar
  27. mybatis-spring-1.2.2.jar
  28. mysql-connector-java-5.1.30-bin.jar
  29. servlet-api.jar
  30. slf4j-api-1.7.7.jar
  31. slf4j-ext-1.7.7.jar
  32. spring-aop-4.0.2.RELEASE.jar
  33. spring-aspects-4.0.2.RELEASE.jar
  34. spring-beans-4.0.2.RELEASE.jar
  35. spring-context-4.0.2.RELEASE.jar
  36. spring-context-support-4.0.2.RELEASE.jar
  37. spring-core-4.0.2.RELEASE.jar
  38. spring-expression-4.0.2.RELEASE.jar
  39. spring-jdbc-4.0.2.RELEASE.jar
  40. spring-oxm-4.0.2.RELEASE.jar
  41. spring-test-4.0.2.RELEASE.jar
  42. spring-tx-4.0.2.RELEASE.jar
  43. spring-web-4.0.4.RELEASE.jar
  44. spring-webmvc-4.0.2.RELEASE.jar
  45. standard-1.1.2.jar

mongodb 关联jar文件

  1. mongo-java-driver-2.10.1.jar
  2. spring-data-commons-core-1.4.0.RELEASE.jar
  3. spring-data-mongodb-1.1.0.RELEASE.jar


项目结构图:


2、配置文件和实列代码

web.xml文件

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <web-app version="2.5"
  3. xmlns="http://java.sun.com/xml/ns/javaee"
  4. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  5. xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
  6. http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
  7. <display-name></display-name>
  8. <context-param>
  9. <param-name>contextConfigLocation</param-name>
  10. <param-value>classpath:spring/spring-context.xml</param-value>
  11. </context-param>
  12. <filter>
  13. <filter-name>encodingFilter</filter-name>
  14. <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
  15. <init-param>
  16. <param-name>encoding</param-name>
  17. <param-value>UTF-8</param-value>
  18. </init-param>
  19. <init-param>
  20. <param-name>forceEncoding</param-name>
  21. <param-value>true</param-value>
  22. </init-param>
  23. </filter>
  24. <filter-mapping>
  25. <filter-name>encodingFilter</filter-name>
  26. <url-pattern>/*</url-pattern>
  27. </filter-mapping>
  28. <listener>
  29. <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  30. </listener>
  31. <servlet>
  32. <servlet-name>springMVC</servlet-name>
  33. <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
  34. <init-param>
  35. <param-name>contextConfigLocation</param-name>
  36. <param-value>classpath:spring-mvc.xml</param-value>
  37. </init-param>
  38. <load-on-startup>1</load-on-startup>
  39. </servlet>
  40. <servlet-mapping>
  41. <servlet-name>springMVC</servlet-name>
  42. <url-pattern>/</url-pattern>
  43. </servlet-mapping>
  44. </web-app>

spring-mvc.xml

  1. <beans xmlns="http://www.springframework.org/schema/beans"
  2. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  3. xmlns:p="http://www.springframework.org/schema/p"
  4. xmlns:context="http://www.springframework.org/schema/context"
  5. xmlns:mvc="http://www.springframework.org/schema/mvc"
  6. xsi:schemaLocation="
  7. http://www.springframework.org/schema/beans
  8. http://www.springframework.org/schema/beans/spring-beans.xsd
  9. http://www.springframework.org/schema/context
  10. http://www.springframework.org/schema/context/spring-context.xsd
  11. http://www.springframework.org/schema/mvc
  12. http://www.springframework.org/schema/mvc/spring-mvc.xsd">
  13. <!-- 开启controller注解支持 -->
  14. <!-- 注意事项请参考:http://jinnianshilongnian.iteye.com/blog/1762632 -->
  15. <context:component-scan base-package="cn.zetark.oauth2.**.web.controller" use-default-filters="false">
  16. <context:include-filter type="annotation"
  17. expression="org.springframework.stereotype.Controller"/>
  18. <context:include-filter type="annotation"
  19. expression="org.springframework.web.bind.annotation.ControllerAdvice"/>
  20. </context:component-scan>
  21. <!--注解标签驱动 -->
  22. <mvc:annotation-driven>
  23. </mvc:annotation-driven>
  24. <!-- 当在web.xml 中 DispatcherServlet使用 <url-pattern>/</url-pattern> 映射时,能映射静态资源 -->
  25. <mvc:default-servlet-handler/>
  26. <!-- 静态资源映射 -->
  27. <mvc:resources mapping="/static/**" location="/WEB-INF/static/"/>
  28. <!-- 默认的视图解析器 在上边的解析错误时使用 (默认使用html)- -->
  29. <bean id="defaultViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver"
  30. p:order="1">
  31. <property name="viewClass" value="org.springframework.web.servlet.view.JstlView"/>
  32. <property name="contentType" value="text/html"/>
  33. <property name="prefix" value="/WEB-INF/jsp/"/>
  34. <property name="suffix" value=".jsp"/>
  35. </bean>
  36. <!--避免IE执行AJAX时,返回JSON出现下载文件 -->
  37. <bean id="mappingJacksonHttpMessageConverter"
  38. class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter">
  39. <property name="supportedMediaTypes">
  40. <list>
  41. <value>text/html;charset=UTF-8</value>
  42. </list>
  43. </property>
  44. </bean>
  45. <!-- 启动SpringMVC的注解功能,完成请求和注解POJO的映射 -->
  46. <bean
  47. class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
  48. <property name="messageConverters">
  49. <list>
  50. <ref bean="mappingJacksonHttpMessageConverter" /> <!-- JSON转换器 -->
  51. </list>
  52. </property>
  53. </bean>
  54. </beans>

spring-context.xml

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <beans xmlns="http://www.springframework.org/schema/beans"
  3. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
  4. xmlns:context="http://www.springframework.org/schema/context"
  5. xmlns:mvc="http://www.springframework.org/schema/mvc"
  6. xmlns:tx="http://www.springframework.org/schema/tx"
  7. xmlns:aop="http://www.springframework.org/schema/aop"
  8. xsi:schemaLocation="http://www.springframework.org/schema/beans
  9. http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
  10. http://www.springframework.org/schema/context
  11. http://www.springframework.org/schema/context/spring-context-3.1.xsd
  12. http://www.springframework.org/schema/tx
  13. http://www.springframework.org/schema/tx/spring-tx-3.1.xsd
  14. http://www.springframework.org/schema/mvc
  15. http://www.springframework.org/schema/mvc/spring-mvc-3.1.xsd
  16. http://www.springframework.org/schema/aop
  17. http://www.springframework.org/schema/aop/spring-aop-3.1.xsd">
  18. <!-- 引入配置文件 -->
  19. <bean id="propertyConfigurer"
  20. class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
  21. <property name="location" value="classpath:jdbc.properties" />
  22. </bean>
  23. <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
  24. destroy-method="close">
  25. <property name="driverClassName" value="${driver}" />
  26. <property name="url" value="${url}" />
  27. <property name="username" value="${username}" />
  28. <property name="password" value="${password}" />
  29. <!-- 初始化连接大小 -->
  30. <property name="initialSize" value="${initialSize}"></property>
  31. <!-- 连接池最大数量 -->
  32. <property name="maxActive" value="${maxActive}"></property>
  33. <!-- 连接池最大空闲 -->
  34. <property name="maxIdle" value="${maxIdle}"></property>
  35. <!-- 连接池最小空闲 -->
  36. <property name="minIdle" value="${minIdle}"></property>
  37. <!-- 获取连接最大等待时间 -->
  38. <property name="maxWait" value="${maxWait}"></property>
  39. </bean>
  40. <!-- spring和MyBatis完美整合,不需要mybatis的配置映射文件 -->
  41. <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
  42. <property name="dataSource" ref="dataSource" />
  43. <!-- 自动扫描mapping.xml文件 -->
  44. <property name="mapperLocations" value="classpath:com/wlsq/oauth/mapper/*.xml"></property>
  45. </bean>
  46. <!-- DAO接口所在包名,Spring会自动查找其下的类 -->
  47. <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
  48. <property name="basePackage" value="com.wlsq.oauth.dao" />
  49. <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"></property>
  50. </bean>
  51. <!-- (事务管理)transaction manager, use JtaTransactionManager for global tx -->
  52. <bean id="transactionManager"
  53. class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
  54. <property name="dataSource" ref="dataSource" />
  55. </bean>
  56. <!-- 通知 -->
  57. <tx:advice id="tx"
  58. transaction-manager="transactionManager">
  59. <tx:attributes>
  60. <tx:method name="delete*" propagation="REQUIRED" />
  61. <tx:method name="insert*" propagation="REQUIRED" />
  62. <tx:method name="update*" propagation="REQUIRED" />
  63. <tx:method name="find*" read-only="true" />
  64. <tx:method name="get*" read-only="true" />
  65. <tx:method name="select*" read-only="true" />
  66. </tx:attributes>
  67. </tx:advice>
  68. <aop:config>
  69. <aop:pointcut id="pc" expression="execution(* com.common.service.*.*(..))" />
  70. <!--把事务控制在Service层-->
  71. <aop:advisor pointcut-ref="pc" advice-ref="tx" />
  72. </aop:config>
  73. <!--ssm 集成 mongodb -->
  74. <import resource="classpath:spring/spring-mongodb.xml"/>
  75. </beans>

spring-mongodb.xml

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <beans xmlns="http://www.springframework.org/schema/beans"
  3. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  4. xmlns:p="http://www.springframework.org/schema/p"
  5. xmlns:mongo="http://www.springframework.org/schema/data/mongo"
  6. xsi:schemaLocation="http://www.springframework.org/schema/beans
  7. http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
  8. http://www.springframework.org/schema/data/mongo
  9. http://www.springframework.org/schema/data/mongo/spring-mongo.xsd
  10. http://www.springframework.org/schema/data/repository
  11. http://www.springframework.org/schema/data/repository/spring-repository-1.4.xsd ">
  12. <!-- Default bean name is 'mongo' -->
  13. <mongo:mongo host="120.25.56.93" port="27017"/>
  14. <!--mongodb 数据库账号和密码信息 -->
  15. <bean id="userCredentials" class="org.springframework.data.authentication.UserCredentials">
  16. <constructor-arg name="username" value="admin"/>
  17. <constructor-arg name="password" value="123456"/>
  18. </bean>
  19. <!-- Offers convenience methods and automatic mapping between MongoDB JSON documents and your domain classes. -->
  20. <bean id="mongoTemplate" class="org.springframework.data.mongodb.core.MongoTemplate">
  21. <constructor-arg ref="mongo"/>
  22. <constructor-arg name="databaseName" value="admin"/>
  23. <constructor-arg ref="userCredentials"/>
  24. </bean>
  25. <bean id="userDao" class="com.wlsq.oauth.dao.impl.UserDao" />
  26. </beans>

mongodb 逻辑封装代码(mongodbTemplate 封装)

  1. package com.wlsq.oauth.dao.support;
  2. import org.springframework.beans.BeansException;
  3. import org.springframework.context.ApplicationContext;
  4. import org.springframework.context.ApplicationContextAware;
  5. import org.springframework.data.mongodb.core.MongoTemplate;
  6. public class AbstractBaseMongoTemplete implements ApplicationContextAware {
  7. protected MongoTemplate mongoTemplate;
  8. /**
  9. * 设置mongoTemplate
  10. * @param mongoTemplate the mongoTemplate to set
  11. */
  12. public void setMongoTemplate(MongoTemplate mongoTemplate) {
  13. this.mongoTemplate = mongoTemplate;
  14. }
  15. public void setApplicationContext(ApplicationContext applicationContext)
  16. throws BeansException {
  17. // TODO Auto-generated method stub
  18. MongoTemplate mongoTemplate = applicationContext.getBean("mongoTemplate", MongoTemplate.class);
  19. setMongoTemplate(mongoTemplate);
  20. }
  21. }

mongodb  dao层数据库接口基类

  1. package com.wlsq.oauth.dao.impl;
  2. import java.util.List;
  3. import org.springframework.data.mongodb.core.query.Criteria;
  4. import org.springframework.data.mongodb.core.query.Query;
  5. import org.springframework.data.mongodb.core.query.Update;
  6. import com.wlsq.oauth.dao.IUserDao;
  7. import com.wlsq.oauth.dao.support.AbstractBaseMongoTemplete;
  8. import com.wlsq.oauth.entity.User;
  9. public class UserDao extends AbstractBaseMongoTemplete implements IUserDao {
  10. /**
  11. * 新增
  12. * <br>------------------------------<br>
  13. * @param user
  14. */
  15. public void insert(User user) {
  16. // TODO Auto-generated method stub
  17. mongoTemplate.insert(user);
  18. }
  19. /**
  20. * 批量新增
  21. * <br>------------------------------<br>
  22. * @param users
  23. */
  24. public void insertAll(List<User> users) {
  25. // TODO Auto-generated method stub
  26. mongoTemplate.insertAll(users);
  27. }
  28. /**
  29. * 删除,按主键id, 如果主键的值为null,删除会失败
  30. * <br>------------------------------<br>
  31. * @param id
  32. */
  33. public void deleteById(String id) {
  34. // TODO Auto-generated method stub
  35. User user = new User(id, null, 0);
  36. mongoTemplate.remove(user);
  37. }
  38. /**
  39. * 按条件删除
  40. * <br>------------------------------<br>
  41. * @param criteriaUser
  42. */
  43. public void delete(User criteriaUser) {
  44. // TODO Auto-generated method stub
  45. Criteria criteria = Criteria.where("age").gt(criteriaUser.getAge());;
  46. Query query = new Query(criteria);
  47. mongoTemplate.remove(query, User.class);
  48. }
  49. /**
  50. * 删除全部
  51. * <br>------------------------------<br>
  52. */
  53. public void deleteAll() {
  54. // TODO Auto-generated method stub
  55. mongoTemplate.dropCollection(User.class);
  56. }
  57. /**
  58. * 按主键修改,
  59. * 如果文档中没有相关key 会新增 使用$set修改器
  60. * <br>------------------------------<br>
  61. * @param user
  62. */
  63. public void updateById(User user) {
  64. // TODO Auto-generated method stub
  65. Criteria criteria = Criteria.where("id").is(user.getId());
  66. Query query = new Query(criteria);
  67. Update update = Update.update("age", user.getAge()).set("name", user.getName());
  68. mongoTemplate.updateFirst(query, update, User.class);
  69. }
  70. /**
  71. * 修改多条
  72. * <br>------------------------------<br>
  73. * @param criteriaUser
  74. * @param user
  75. */
  76. public void update(User criteriaUser, User user) {
  77. // TODO Auto-generated method stub
  78. Criteria criteria = Criteria.where("age").gt(criteriaUser.getAge());;
  79. Query query = new Query(criteria);
  80. Update update = Update.update("name", user.getName()).set("age", user.getAge());
  81. mongoTemplate.updateMulti(query, update, User.class);
  82. }
  83. /**
  84. * 根据主键查询
  85. * <br>------------------------------<br>
  86. * @param id
  87. * @return
  88. */
  89. public User findById(String id) {
  90. // TODO Auto-generated method stub
  91. return mongoTemplate.findById(id, User.class);
  92. }
  93. /**
  94. * 查询全部
  95. * <br>------------------------------<br>
  96. * @return
  97. */
  98. public List<User> findAll() {
  99. // TODO Auto-generated method stub
  100. return mongoTemplate.findAll(User.class);
  101. }
  102. /**
  103. * 按条件查询, 分页
  104. * <br>------------------------------<br>
  105. * @param criteriaUser
  106. * @param skip
  107. * @param limit
  108. * @return
  109. */
  110. public List<User> find(User criteriaUser, int skip, int limit) {
  111. // TODO Auto-generated method stub
  112. Query query = getQuery(criteriaUser);
  113. query.skip(skip);
  114. query.limit(limit);
  115. return mongoTemplate.find(query, User.class);
  116. }
  117. /**
  118. * 根据条件查询出来后 再去修改
  119. * <br>------------------------------<br>
  120. * @param criteriaUser 查询条件
  121. * @param updateUser 修改的值对象
  122. * @return
  123. */
  124. public User findAndModify(User criteriaUser, User updateUser) {
  125. // TODO Auto-generated method stub
  126. Query query = getQuery(criteriaUser);
  127. Update update = Update.update("age", updateUser.getAge()).set("name", updateUser.getName());
  128. return mongoTemplate.findAndModify(query, update, User.class);
  129. }
  130. /**
  131. * 查询出来后 删除
  132. * <br>------------------------------<br>
  133. * @param criteriaUser
  134. * @return
  135. */
  136. public User findAndRemove(User criteriaUser) {
  137. // TODO Auto-generated method stub
  138. Query query = getQuery(criteriaUser);
  139. return mongoTemplate.findAndRemove(query, User.class);
  140. }
  141. /**
  142. * count
  143. * <br>------------------------------<br>
  144. * @param criteriaUser
  145. * @return
  146. */
  147. public long count(User criteriaUser) {
  148. // TODO Auto-generated method stub
  149. Query query = getQuery(criteriaUser);
  150. return mongoTemplate.count(query, User.class);
  151. }
  152. /**
  153. *
  154. * <br>------------------------------<br>
  155. * @param criteriaUser
  156. * @return
  157. */
  158. private Query getQuery(User criteriaUser) {
  159. if (criteriaUser == null) {
  160. criteriaUser = new User();
  161. }
  162. Query query = new Query();
  163. if (criteriaUser.getId() != null) {
  164. Criteria criteria = Criteria.where("id").is(criteriaUser.getId());
  165. query.addCriteria(criteria);
  166. }
  167. if (criteriaUser.getAge() > 0) {
  168. Criteria criteria = Criteria.where("age").gt(criteriaUser.getAge());
  169. query.addCriteria(criteria);
  170. }
  171. if (criteriaUser.getName() != null) {
  172. Criteria criteria = Criteria.where("name").regex("^" + criteriaUser.getName());
  173. query.addCriteria(criteria);
  174. }
  175. return query;
  176. }
  177. }

  1. package com.wlsq.oauth.dao;
  2. import java.util.List;
  3. import com.wlsq.oauth.entity.User;
  4. public interface IUserDao {
  5. /**
  6. * 新增
  7. * <br>------------------------------<br>
  8. * @param user
  9. */
  10. void insert(User user);
  11. /**
  12. * 新增
  13. * <br>------------------------------<br>
  14. * @param users
  15. */
  16. void insertAll(List<User> users);
  17. /**
  18. * 删除,主键id, 如果主键的值为null,删除会失败
  19. * <br>------------------------------<br>
  20. * @param id
  21. */
  22. void deleteById(String id);
  23. /**
  24. * 按条件删除
  25. * <br>------------------------------<br>
  26. * @param criteriaUser
  27. */
  28. void delete(User criteriaUser);
  29. /**
  30. * 删除全部
  31. * <br>------------------------------<br>
  32. */
  33. void deleteAll();
  34. /**
  35. * 修改
  36. * <br>------------------------------<br>
  37. * @param user
  38. */
  39. void updateById(User user);
  40. /**
  41. * 更新多条
  42. * <br>------------------------------<br>
  43. * @param criteriaUser
  44. * @param user
  45. */
  46. void update(User criteriaUser, User user);
  47. /**
  48. * 根据主键查询
  49. * <br>------------------------------<br>
  50. * @param id
  51. * @return
  52. */
  53. User findById(String id);
  54. /**
  55. * 查询全部
  56. * <br>------------------------------<br>
  57. * @return
  58. */
  59. List<User> findAll();
  60. /**
  61. * 按条件查询
  62. * <br>------------------------------<br>
  63. * @param criteriaUser
  64. * @param skip
  65. * @param limit
  66. * @return
  67. */
  68. List<User> find(User criteriaUser, int skip, int limit);
  69. /**
  70. * 根据条件查询出来后 在去修改
  71. * <br>------------------------------<br>
  72. * @param criteriaUser 查询条件
  73. * @param updateUser 修改的值对象
  74. * @return
  75. */
  76. User findAndModify(User criteriaUser, User updateUser);
  77. /**
  78. * 查询出来后 删除
  79. * <br>------------------------------<br>
  80. * @param criteriaUser
  81. * @return
  82. */
  83. User findAndRemove(User criteriaUser);
  84. /**
  85. * count
  86. * <br>------------------------------<br>
  87. * @param criteriaUser
  88. * @return
  89. */
  90. long count(User criteriaUser);
  91. }

mongodb 实体类

  1. package com.wlsq.oauth.entity;
  2. import java.io.Serializable;
  3. public class User implements Serializable {
  4. /**
  5. *
  6. */
  7. private static final long serialVersionUID = -2634064977259616340L;
  8. private String id;
  9. private String name;
  10. private int age;
  11. public User() {
  12. }
  13. public User(String id, String name, int age) {
  14. super();
  15. this.id = id;
  16. this.name = name;
  17. this.age = age;
  18. }
  19. public String getId() {
  20. return id;
  21. }
  22. public void setId(String id) {
  23. this.id = id;
  24. }
  25. public String getName() {
  26. return name;
  27. }
  28. public void setName(String name) {
  29. this.name = name;
  30. }
  31. public int getAge() {
  32. return age;
  33. }
  34. public void setAge(int age) {
  35. this.age = age;
  36. }
  37. }


声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/IT小白/article/detail/319716
推荐阅读
相关标签
  

闽ICP备14008679号