发现一入手 MongoDB,便无法脱离,简要说一下,MongoDB 是一个介于关系数据库和非关系数据库之间的产品,是非关系数据库当中功能最丰富,最像关系数据库的。
也是在 Nosql 中我最喜欢的一种数据库,MongoDB 将数据存储为一个文档,数据结构由键值(key=>value)对组成。MongoDB 文档类似于 JSON 对象。字段值可以包含其他文档,数组及文档数组。
谈一下关系型数据库(RDBMS)与 MongoDB 的对应关系:
建立 maven 工程,需要导入与 MongoDB 相关的驱动包:
1 <!--MongoDB驱动包-->
2 <dependency>
3 <groupId>org.mongodb</groupId>
4 <artifactId>mongo-java-driver</artifactId>
5 <version>3.1.0</version>
6 </dependency>
7 <!--MongoDB核心包-->
8 <dependency>
9 <groupId>org.springframework.data</groupId>
10 <artifactId>spring-data-mongodb</artifactId>
11 <version>1.8.2.RELEASE</version>
12 </dependency>
幸运的是,spring data mongodb 提供的 MongoTemplate 模板对数据库的操作变得十分简单,在 dao 层做一个接口和实现类,创建一个 MongoTemplate 对象,就可以完成数据库一些相关操作。
话不多说,直接来干货:
先看看目录结构:
1 <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
2 xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
3 <modelVersion>4.0.0</modelVersion>
4 <groupId>com.krry</groupId>
5 <artifactId>krry_mongodb</artifactId>
6 <packaging>war</packaging>
7 <version>1.0-SNAPSHOT</version>
8 <name>krry_mongodb Maven Webapp</name>
9 <url>http://maven.apache.org</url>
10
11 <dependencies>
12 <!--引入servlet -->
13 <dependency>
14 <groupId>javax.servlet</groupId>
15 <artifactId>servlet-api</artifactId>
16 <version>3.0-alpha-1</version>
17 <scope>provided</scope>
18 </dependency>
19 <!--引入jstl的包 -->
20 <dependency>
21 <groupId>jstl</groupId>
22 <artifactId>jstl</artifactId>
23 <version>1.2</version>
24 <scope>provided</scope>
25 </dependency>
26
27 <!--引入jsp的编译依赖 -->
28 <dependency>
29 <groupId>javax.servlet.jsp</groupId>
30 <artifactId>jsp-api</artifactId>
31 <version>2.2</version>
32 <scope>provided</scope>
33 </dependency>
34
35 <!--引入log4j -->
36 <dependency>
37 <groupId>log4j</groupId>
38 <artifactId>log4j</artifactId>
39 <version>1.2.17</version>
40 </dependency>
41
42 <dependency>
43 <groupId>org.apache.commons</groupId>
44 <artifactId>commons-lang3</artifactId>
45 <version>3.3.2</version>
46 </dependency>
47
48
49 <!--MongoDB驱动包-->
50 <dependency>
51 <groupId>org.mongodb</groupId>
52 <artifactId>mongo-java-driver</artifactId>
53 <version>3.1.0</version>
54 </dependency>
55 <!--MongoDB核心包-->
56 <dependency>
57 <groupId>org.springframework.data</groupId>
58 <artifactId>spring-data-mongodb</artifactId>
59 <version>1.8.2.RELEASE</version>
60 </dependency>
61
62 <!--引入junit -->
63 <dependency>
64 <groupId>junit</groupId>
65 <artifactId>junit</artifactId>
66 <version>4.11</version>
67 <scope>test</scope>
68 </dependency>
69
70 <!--spring springmvc mybatis -->
71 <!-- spring和springmvc相关的构建 jar -->
72 <dependency>
73 <groupId>org.springframework</groupId>
74 <artifactId>spring-context</artifactId>
75 <version>4.0.2.RELEASE</version>
76 </dependency>
77
78 <dependency>
79 <groupId>org.springframework</groupId>
80 <artifactId>spring-jdbc</artifactId>
81 <version>4.0.2.RELEASE</version>
82 </dependency>
83
84 <!-- springmvc相关 -->
85 <dependency>
86 <groupId>org.springframework</groupId>
87 <artifactId>spring-webmvc</artifactId>
88 <version>4.0.2.RELEASE</version>
89 </dependency>
90
91 <dependency>
92 <groupId>org.apache.commons</groupId>
93 <artifactId>commons-lang3</artifactId>
94 <version>3.3.2</version>
95 </dependency>
96
97
98 </dependencies>
99
100 </project>
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:context="http://www.springframework.org/schema/context"
5 xmlns:mongo="http://www.springframework.org/schema/data/mongo"
6 xsi:schemaLocation="http://www.springframework.org/schema/context
7 http://www.springframework.org/schema/context/spring-context-3.0.xsd
8 http://www.springframework.org/schema/beans
9 http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
10 http://www.springframework.org/schema/data/mongo
11 http://www.springframework.org/schema/data/mongo/spring-mongo.xsd
12 http://www.springframework.org/schema/tx
13 http://www.springframework.org/schema/tx/spring-tx.xsd
14 ">
15
16
17 <!-- 加载mongodb的属性配置文件 -->
18 <context:property-placeholder location="classpath:mongodb.properties" />
19
20 <!--1.开启注解-->
21 <context:annotation-config/>
22
23 <!--2.配置包扫描 -->
24 <context:component-scan base-package="com.krry">
25 <!--过滤掉控制层的注解 -->
26 <context:exclude-filter type="annotation"
27 expression="org.springframework.stereotype.Controller"/>
28 </context:component-scan>
29
30 <!--3.服务器连接信息-->
31 <mongo:mongo-client host="${mongo.host}" port="${mongo.port}"></mongo:mongo-client>
32
33 <!--4.创建mongoTemplate模板-->
34 <bean id="mongoTemplate" class="org.springframework.data.mongodb.core.MongoTemplate">
35 <constructor-arg ref="mongo"/>
36 <!-- 设置使用的数据库 名-->
37 <constructor-arg name="databaseName" value="${mongo.dbname}"/>
38 </bean>
39
40
41 </beans>
1 #mongoDB\u8FDE\u63A5\u914D\u7F6E
2 mongo.dbname=krry_test
3 mongo.host=127.0.0.1
4 mongo.port=27017
5 #mongo.username=root
6 #mongo.password=root
7 #\u4E00\u4E2A\u7EBF\u7A0B\u53D8\u4E3A\u53EF\u7528\u7684\u6700\u5927\u963B\u585E\u6570
8 mongo.connectionsPerHost=8
9 #\u7EBF\u7A0B\u961F\u5217\u6570,\u5B83\u4EE5\u4E0A\u9762connectionsPerHost\u503C\u76F8\u4E58\u7684\u7ED3\u679C\u5C31\u662F\u7EBF\u7A0B\u961F\u5217\u6700\u5927\u503C
10 mongo.threadsAllowedToBlockForConnectionMultiplier=4
11 #\u8FDE\u63A5\u8D85\u65F6\u65F6\u95F4\uFF08\u6BEB\u79D2\uFF09
12 mongo.connectTimeout=1500
13 #\u6700\u5927\u7B49\u5F85\u65F6\u95F4
14 mongo.maxWaitTime=1500
15 #\u81EA\u52A8\u91CD\u8FDE
16 mongo.autoConnectRetry=true
17 #scoket\u4FDD\u6301\u6D3B\u52A8
18 mongo.socketKeepAlive= true
19 #scoket\u8D85\u65F6\u65F6\u95F4
20 mongo.socketTimeout=1500
21 #\u8BFB\u5199\u5206\u79BB
22 mongo.slaveOk=true
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:context="http://www.springframework.org/schema/context"
6 xmlns:util="http://www.springframework.org/schema/util"
7 xmlns:mvc="http://www.springframework.org/schema/mvc"
8 xsi:schemaLocation="http://www.springframework.org/schema/beans
9 http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
10 http://www.springframework.org/schema/context
11 http://www.springframework.org/schema/context/spring-context-3.0.xsd
12 http://www.springframework.org/schema/util
13 http://www.springframework.org/schema/util/spring-util-3.0.xsd
14 http://www.springframework.org/schema/mvc
15 http://www.springframework.org/schema/mvc/spring-mvc.xsd
16 ">
17
18 <!-- 扫包 -->
19 <context:component-scan base-package="com.krry.controller"></context:component-scan>
20
21
22 <!--以下映射器和适配器的配置可以通过注解驱动来代替 -->
23 <mvc:annotation-driven></mvc:annotation-driven>
24
25
26 <!--对静态资源文件的访问 必须要设置,因为在springmvc的配置中配置了/匹配所有请求,
27 此工程所有的请求(.do ,addUser,js/image/css)都会被springmvc解析,
28 必须对所有的静态资源文件进行过滤放行 -->
29 <mvc:resources mapping="/resource/**" location="/resource/" />
30
31 <!-- 拦截器定义 -->
32 <mvc:interceptors>
33 <mvc:interceptor>
34 <!-- 个人中心也需要登陆 以admin开头的配置都会进行拦截-->
35 <mvc:mapping path="/admin/**"></mvc:mapping>
36 <!-- 这个是设置不会进入拦截器的路径 -->
37 <mvc:exclude-mapping path="/resource/**"/>
38 <!-- 拦截器进入的类,返回false表示不会进入输入的路径 -->
39 <bean class="com.krry.core.LoginInterceptor" />
40 </mvc:interceptor>
41 </mvc:interceptors>
42
43 <!-- 视图渲染 jsp/freemaker/velocity-->
44 <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
45 <!-- 制定页面存放的路径 -->
46 <property name="prefix" value="/WEB-INF/pages/"></property>
47 <!-- 文件的后缀 -->
48 <property name="suffix" value=".jsp"></property>
49 </bean>
50
51 </beans>
1 <?xml version="1.0" encoding="UTF-8"?>
2 <web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee"
3 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
4 xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
5 http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
6
7 <display-name>krry_mongodb</display-name>
8
9 <welcome-file-list>
10 <welcome-file>index/index</welcome-file>
11 </welcome-file-list>
12
13 <!-- 加载Spring IOC容器 -->
14 <context-param>
15 <param-name>contextConfigLocation</param-name>
16 <param-value>classpath:applicationContext.xml</param-value>
17 </context-param>
18
19 <!-- spring上下文监听器 -->
20 <listener>
21 <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
22 </listener>
23
24 <!-- Introspector缓存清除监听器 -->
25 <listener>
26 <listener-class>org.springframework.web.util.IntrospectorCleanupListener</listener-class>
27 </listener>
28
29 <filter>
30 <filter-name>encoding</filter-name>
31 <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
32 <init-param>
33 <param-name>encoding</param-name>
34 <param-value>UTF-8</param-value>
35 </init-param>
36 </filter>
37
38 <filter-mapping>
39 <filter-name>encoding</filter-name>
40 <url-pattern>/*</url-pattern>
41 </filter-mapping>
42
43 <!-- 配置DispatcherServlet -->
44 <servlet>
45 <servlet-name>krry_mongodb</servlet-name>
46 <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
47 <!-- 配置springMVC的配置文件 -->
48 <!-- 如果不配置下面选项,系统默认加载classpath下面名为[servlet-name]-servlet.xml的文件 springmvc01-servlet.xml -->
49 <init-param>
50 <param-name>contextConfigLocation</param-name>
51 <param-value>classpath:springmvc.xml</param-value>
52 </init-param>
53 </servlet>
54
55 <!-- 这里再配一次,才可以使用欢迎页
56 标签里面一定要以/开头,与欢迎页的区别就是这里
57 <url-pattern>/...</url-pattern> -->
58 <servlet-mapping>
59 <servlet-name>krry_mongodb</servlet-name>
60 <url-pattern>/index/index</url-pattern>
61 </servlet-mapping>
62
63 <!-- 可以配*.do, *.action(了解) / (重点): 所有的请求都会被spring mvc解析,但必须对静态资源文件进行过滤放行,建议大家使用这种方式
64 /* : 不建议大家使用 -->
65 <servlet-mapping>
66 <servlet-name>krry_mongodb</servlet-name>
67 <url-pattern>/</url-pattern>
68 </servlet-mapping>
69
70 </web-app>
71
72
73
1 package com.krry.dao;
2
3 import java.util.List;
4
5 import com.krry.entity.User;
6
7 /**
8 *
9 * @author
10 */
11 public interface IUserDao {
12
13 /**
14 * 添加
15 * @param User
16 */
17 public void addUser(User User);
18
19
20 /**
21 * 删除
22 * @param id
23 */
24 public void removeUser(String id);
25
26
27 /**
28 * 保存或修改
29 * @param User
30 */
31 public void saveOrUpdateUser(User User);
32
33
34 /**
35 * 根据id查询单个
36 * @param id
37 * @return
38 */
39 public User findById(String id);
40
41 /**
42 * 根据用户名查询
43 * @param id
44 * @return
45 */
46 public User findByUsername(String username);
47
48
49 /**
50 * 查询所有
51 * @return
52 */
53 public List<User> findAll();
54
55
56 }
1 package com.krry.dao.impl;
2
3 import org.springframework.beans.factory.annotation.Autowired;
4 import org.springframework.data.mongodb.core.MongoTemplate;
5 import org.springframework.data.mongodb.core.query.Criteria;
6 import org.springframework.data.mongodb.core.query.Query;
7 import org.springframework.stereotype.Repository;
8
9 import com.krry.dao.IUserDao;
10 import com.krry.entity.User;
11
12 import java.util.List;
13
14 /**
15 * @author
16 */
17 @Repository
18 public class UserDaoImpl implements IUserDao {
19
20 @Autowired
21 private MongoTemplate mongoTemplate;
22
23 public void addUser(User User) {
24 //1.如果没有指定集合,则默认添加到和对象名称相同的集合中,没有则创建一个
25 //2.也可以指定集合 mongoTemplate.save(User, "User_db");
26 mongoTemplate.save(User);
27 }
28
29 public void removeUser(String id) {
30
31 User User = findById(id);
32 mongoTemplate.remove(User);
33 }
34
35 public void saveOrUpdateUser(User User) {
36
37 mongoTemplate.save(User);
38 }
39
40 public User findById(String id) {
41
42 return mongoTemplate.findById(id, User.class);
43 }
44
45 public List<User> findAll() {
46
47 return mongoTemplate.findAll(User.class);
48 }
49
50 public User findByUsername(String username) {
51 //根据username查询
52 Query sql = new Query(Criteria.where("username").is(username));
53
54 return mongoTemplate.findOne(sql,User.class);
55 }
56 }
1 package com.krry.entity;
2
3 import org.springframework.data.annotation.Id;
4 import org.springframework.data.mongodb.core.mapping.Document;
5 import org.springframework.data.mongodb.core.mapping.Field;
6
7
8 /**
9 * @Document(collection = "user")这个注解和Hibernate的注解Entiry非常相似,
10 * 就是定义一个文档,对象MongoDB存储的Collection(表)的名称是user
11 * @Id指该字段是主键,不能缺少
12 * @Field("username")指该字段映射MongoDB的实际字段,如果一致可以省略、
13 *
14 * User
15 * @author krry
16 * @version 1.0.0
17 *
18 */
19 @Document(collection = "user")
20 public class User {
21
22 //主键
23 @Id
24 private String id;
25 //用户名
26 @Field("username")
27 private String username;
28 //密码
29 private String password;
30 //建时间
31 private String createTime;
32
33 public User() {
34
35 }
36
37 public User(String username,String password,String createTime) {
38 this.username = username;
39 this.password = password;
40 this.createTime = createTime;
41 }
42
43 public String getCreateTime() {
44 return createTime;
45 }
46
47 public void setCreateTime(String createTime) {
48 this.createTime = createTime;
49 }
50
51
52 public String getId() {
53 return id;
54 }
55
56 public void setId(String id) {
57 this.id = id;
58 }
59
60 public String getUsername() {
61 return username;
62 }
63
64 public void setUsername(String username) {
65 this.username = username;
66 }
67
68 public String getPassword() {
69 return password;
70 }
71
72 public void setPassword(String password) {
73 this.password = password;
74 }
75
76 @Override
77 public String toString() {
78 return "User [id=" + id + ", username=" + username + ", password="
79 + password + ", createTime=" + createTime + "]";
80 }
81
82
83
84 }
1 package com.krry.controller;
2
3 import java.text.SimpleDateFormat;
4 import java.util.Date;
5
6 import javax.servlet.http.HttpServletRequest;
7
8 import org.springframework.beans.factory.annotation.Autowired;
9 import org.springframework.stereotype.Controller;
10 import org.springframework.web.bind.annotation.RequestMapping;
11 import org.springframework.web.bind.annotation.RequestMethod;
12
13 import com.krry.dao.IUserDao;
14 import com.krry.entity.User;
15 import com.krry.util.TmStringUtils;
16
17 /**
18 * Controller层,作为请求转发
19 * 页面所有路径的访问方法:控制层的命名空间+@RequestMapping的value
20 * */
21 @Controller
22 @RequestMapping("/index")
23 public class KrryController {
24
25 @Autowired
26 private IUserDao userDao;
27
28 /**
29 * 进入首页
30 * @return
31 */
32 @RequestMapping("/index")
33 public String index(){
34
35 return "index/index"; //默认是转发,不会显示转发路径
36 }
37
38 /**
39 * 进入登录界面
40 * @return
41 */
42 @RequestMapping("/login")
43 public String login(){
44
45 return "index/login"; //默认是转发,不会显示转发路径
46 }
47
48
49
50 /**
51 * 点击登录
52 * com.krry.controller.login
53 * 方法名:login
54 * @author krry
55 * @param request
56 * @return String
57 * @exception
58 * @since 1.0.0
59 */
60 @RequestMapping(method=RequestMethod.POST,value="/logined")
61 public String login(HttpServletRequest request){
62 //获取用户和密码
63 String username = request.getParameter("username");
64 String password = request.getParameter("password");
65
66 //如果邮箱和密码为null,那么就返回已null标识
67 if(TmStringUtils.isEmpty(username)) return "index/allError";
68 if(TmStringUtils.isEmpty(password)) return "index/allError";
69
70 //根据邮箱或昵称查询,用户是否存在
71 User user = userDao.findByUsername(username);
72
73 //如果存在
74 if(user!=null){
75
76 if(password.equals(user.getPassword())){
77 //如果密码正确
78 //将用户信息放入到会话中...
79 request.getSession().setAttribute("user", user);
80
81 //这里使用重定向 ,重定向到当前命名空间下@RequestMapping是index的方法
82 return "redirect:index";
83 }else{
84 //如果密码错误
85 System.out.println("密码错误");
86 return "index/error";
87 }
88 }else{
89 //如果不存在,代码邮箱和密码输入有误
90 System.out.println("用户不存在");
91 return "index/error";
92 }
93 }
94
95 /**
96 * 退出登录控制层
97 * com.krry.controller.login
98 * 方法名:logout
99 * @author krry
100 * @param request
101 * @return String
102 * @exception
103 * @since 1.0.0
104 */
105 @RequestMapping(method=RequestMethod.GET,value="/logout")
106 public String logout(HttpServletRequest request){
107 request.getSession().invalidate(); //清空session值
108 return "index/index";
109 }
110
111 /**
112 * 打开注册界面层
113 * @return
114 */
115 @RequestMapping("/rege")
116 public String rege(){
117
118 return "index/resgi";
119 }
120
121 /**
122 * 注册控制层
123 * com.krry.controller.login
124 * 方法名:resig
125 * @author krry
126 * @param request
127 * @return String
128 * @exception
129 * @since 1.0.0
130 */
131 @RequestMapping(method=RequestMethod.POST,value="/resig")
132 public String resig(HttpServletRequest request){
133 //获取用户和密码
134 String username = request.getParameter("username");
135 String password = request.getParameter("password");
136
137 //如果邮箱和密码为null,那么就返回已null标识
138 if(TmStringUtils.isEmpty(username) )return "index/allError";
139 if(TmStringUtils.isEmail(password))return "index/allError";
140
141 //根据昵称查询,用户是否存在
142 User user = userDao.findByUsername(username);
143
144 //若存在
145 if(user != null){ //昵称重复
146 return "index/allError";
147 }
148
149 //格式化时间类型
150 SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
151 String nowTime = sdf.format(new Date());
152
153 //执行到这里,说明可以注册
154 User newUser = new User(username, password, nowTime);
155 //调用注册方法
156 userDao.saveOrUpdateUser(newUser);
157
158 //将信息设置session作用域
159 request.getSession().setAttribute("user", newUser);
160
161 return "redirect:index";
162 }
163
164 }
上面的文件,关键代码均有注释。
细心,总结,也不要死坑于一点,善于转化
GitHub:https://github.com/Krryxa