第11章 SpringBoot集成mongodb开发
本章我们通过SpringBoot集成mongodb,Java,Kotlin开发一个极简社区文章博客系统。
为什么是mongodb?
Mongo 的主要目标是在键/值存储方式(提供了高性能和高度伸缩性)和传统的RDBMS 系统(具有丰富的功能)之间架起一座桥梁,它集两者的优势于一身。Mongo 的BSON 数据格式非常适合文档化格式的存储及查询。[1]
关于nosql和rdbms的对比以及选择,我参考了不少资料,关键一点在于:nosql可以轻易扩展表的列,对于业务快速变化的应用场景非常适合;rdbms则需要安装关系型数据库模式对业务进行建模,适合业务场景已经成熟的系统。我目前的这个项目——dailyReport,我暂时没法确定的是,对于一个report,它的属性应该有哪些:date、title、content、address、images等等,基于此我选择mongodb作为该项目的持久化存储。
11.1 系统基本功能
1.支持markdown编辑器
2.写文章,编辑文章,阅读文章基础博客功能
3.文章列表排序,搜索
11.2 系统技术框架
开发环境:
MacOS Sierra
IDEA 2017.1
JDK 1.8.0_40
mongod-3.2.4
Gradle 3.5-rc-2
后端:
开发语言:Java 混合Kotlin语言开发
开发框架:
kotlinVersion = '1.1.0'
SpringBootVersion = '1.5.2.RELEASE'
Spring-data-mongodb
前端:
JavaScript、html、css
requirejs
jquery
bootstrap
dataTables
meditor
11.3 系统架构设计
领域模型
前后端分层
11.4 数据库环境配置
1.build.gradle配置
添加mongodb starter
compile('org.springframework.boot:spring-boot-starter-data-jpa')
compile('org.springframework.boot:spring-boot-starter-data-mongodb')
添加mongo-java-driver
compile('org.mongodb:mongo-java-driver:3.4.2')
完整配置如下:
group = 'com.restfeel'
version = '0.0.1-SNAPSHOT'
description = ""
apply {
plugin "kotlin"
plugin "kotlin-spring"
plugin "kotlin-jpa"
plugin "org.springframework.boot"
plugin 'java'
plugin 'eclipse'
plugin 'idea'
plugin 'war'
plugin 'maven'
}
sourceCompatibility = 1.8
targetCompatibility = 1.8
sourceSets {
main {
kotlin { srcDir "src/main/kotlin" }
java { srcDir "src/main/java" }
}
test {
kotlin { srcDir "src/test/kotlin" }
java { srcDir "src/test/java" }
}
}
jar {
baseName = 'restfeel'
version = '0.0.1'
}
buildscript {
ext {
kotlinVersion = '1.1.0'
springBootVersion = '1.5.2.RELEASE'
}
dependencies {
classpath "org.springframework.boot:spring-boot-gradle-plugin:$springBootVersion"
classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlinVersion"
classpath "org.jetbrains.kotlin:kotlin-noarg:$kotlinVersion"
classpath "org.jetbrains.kotlin:kotlin-allopen:$kotlinVersion"
}
repositories {
mavenLocal()
mavenCentral()
maven { url "http://oss.jfrog.org/artifactory/oss-release-local" }
maven { url "http://jaspersoft.artifactoryonline.com/jaspersoft/jaspersoft-repo/" }
maven { url "https://oss.sonatype.org/content/repositories/snapshots" }
}
}
dependencies {
compile("org.jetbrains.kotlin:kotlin-stdlib:$kotlinVersion")
compile("org.jetbrains.kotlin:kotlin-reflect:$kotlinVersion")
compile("com.fasterxml.jackson.module:jackson-module-kotlin:2.8.4")
compile('org.springframework.boot:spring-boot-starter')
compile('org.springframework.boot:spring-boot-starter-data-jpa')
compile('org.springframework.boot:spring-boot-starter-data-mongodb')
compile('org.springframework.boot:spring-boot-starter-actuator')
compile('org.springframework.boot:spring-boot-starter-web')
compile('org.springframework.boot:spring-boot-starter-security')
compile('org.springframework.boot:spring-boot-starter-remote-shell')
compile('org.springframework.boot:spring-boot-starter-aop')
providedCompile('org.springframework.boot:spring-boot-starter-tomcat')
compile('javax.servlet:jstl')
providedCompile('org.apache.tomcat.embed:tomcat-embed-jasper')
//thymeleaf
// compile("org.springframework.boot:spring-boot-starter-thymeleaf")
compile('org.hibernate:hibernate-validator:5.1.3.Final')
compile('org.mongodb:mongo-java-driver:3.4.2')
compile('org.hsqldb:hsqldb:2.3.2')
compile('org.apache.httpcomponents:httpclient:4.5.1')
compile('org.apache.httpcomponents:httpmime:4.5.1')
compile('org.apache.commons:commons-lang3:3.3.2')
compile('com.sendgrid:sendgrid-java:2.1.0')
compile('com.ryantenney.metrics:metrics-spring:3.0.0')
compile('net.sf.jasperreports:jasperreports:6.0.0') {
exclude module: 'jdtcore'
exclude module: 'jackson-annotations'
}
compile('com.mangofactory:swagger-springmvc:0.9.4')
compile('org.ajar:swagger-spring-mvc-ui:0.4')
compile('com.google.oauth-client:google-oauth-client:1.19.0')
compile('com.jayway.jsonpath:json-path:2.0.0')
compile('io.swagger:swagger-compat-spec-parser:1.0.12')
compile('org.raml:raml-parser:0.8.12') {
exclude module: 'slf4j-log4j12'
exclude module: 'log4j'
}
testCompile('org.springframework.boot:spring-boot-starter-test')
// https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-devtools
compile group: 'org.springframework.boot', name: 'spring-boot-devtools'
}
compileJava {
//options.fork = true
options.incremental = true
}
repositories {
mavenLocal()
mavenCentral()
maven { url "http://oss.jfrog.org/artifactory/oss-release-local" }
maven { url "http://jaspersoft.artifactoryonline.com/jaspersoft/jaspersoft-repo/" }
maven { url "https://oss.sonatype.org/content/repositories/snapshots" }
}
2.实现AbstractMongoConfiguration类
package com.restfeel.config
import com.mongodb.Mongo
import com.mongodb.MongoClient
import com.mongodb.MongoCredential
import com.mongodb.ServerAddress
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.context.annotation.Bean
import org.springframework.context.annotation.Configuration
import org.springframework.core.env.Environment
import org.springframework.data.mongodb.config.AbstractMongoConfiguration
import org.springframework.data.mongodb.repository.config.EnableMongoRepositories
/**
* Created by jack on 2017/3/29.
*/
@Configuration
@EnableMongoRepositories(*arrayOf("com.restfeel.dao", "com.restfeel.service"))
class PersistenceConfig : AbstractMongoConfiguration() {
@Autowired
private val env: Environment? = null
override fun getDatabaseName(): String {
return env!!.getProperty("mongodb.name")
}
@Bean
@Throws(Exception::class)
override fun mongo(): Mongo {
return MongoClient(listOf(ServerAddress(env!!.getProperty("mongodb.host"), env!!.getProperty("mongodb.port", Int::class.java))),
listOf(MongoCredential
.createCredential(env!!.getProperty("mongodb.username"), env!!.getProperty("mongodb.name"),
env!!.getProperty("mongodb.password").toCharArray())))
}
// override fun getMappingBasePackage(): String {
// return "com.restfiddle.dao"
// }
/**
* 这地方是配置扫描继承Repository类的所有接口类的路径的,路径配置错误,bean就不会创建了。
* 东海陈光剑 Jason Chen @蒋村花园如意苑 2017.3.30 01:41:35
*/
override fun getMappingBasePackages(): Collection<String> {
return setOf("com.restfeel.dao", "com.restfeel.service")
}
}
11.5 定义领域对象
package com.restfeel.entity
import org.bson.types.ObjectId
import org.springframework.data.mongodb.core.mapping.Document
import java.util.*
import javax.persistence.GeneratedValue
import javax.persistence.GenerationType
import javax.persistence.Id
import javax.persistence.Version
@Document(collection = "blog") // 如果不指定collection,默认遵从命名规则
class Blog {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
var id: String = ObjectId.get().toString()
@Version
var version: Long = 0
var title: String = ""
var content: String = ""
var author: String = ""
var gmtCreated: Date = Date()
var gmtModified: Date = Date()
var isDeleted: Int = 0 //1 Yes 0 No
var deletedDate: Date = Date()
override fun toString(): String {
return "Blog(id='$id', version=$version, title='$title', content='$content', author='$author', gmtCreated=$gmtCreated, gmtModified=$gmtModified, isDeleted=$isDeleted, deletedDate=$deletedDate)"
}
}
11.6 核心业务逻辑实现
BlogService代码:
package com.restfeel.service
import com.restfeel.entity.Blog
import org.springframework.data.mongodb.repository.MongoRepository
import org.springframework.data.mongodb.repository.Query
import org.springframework.data.repository.query.Param
interface BlogService : MongoRepository<Blog, String> {
@Query("{ 'title' : ?0 }")
fun findByTitle(@Param("title") title: String): Iterable<Blog>
}
BlogController代码:
package com.restfeel.controller
import com.restfeel.entity.Blog
import com.restfeel.service.BlogService
import org.springframework.boot.autoconfigure.EnableAutoConfiguration
import org.springframework.context.annotation.ComponentScan
import org.springframework.security.core.context.SecurityContextHolder
import org.springframework.security.core.userdetails.UserDetails
import org.springframework.stereotype.Controller
import org.springframework.transaction.annotation.Propagation
import org.springframework.transaction.annotation.Transactional
import org.springframework.ui.Model
import org.springframework.web.bind.annotation.GetMapping
import org.springframework.web.bind.annotation.PostMapping
import org.springframework.web.bind.annotation.RequestParam
import org.springframework.web.bind.annotation.ResponseBody
import java.util.*
import javax.servlet.http.HttpServletRequest
/**
* 文章列表,写文章的Controller
* @author Jason Chen 2017/3/31 01:10:16
*/
@Controller
@EnableAutoConfiguration
@ComponentScan
@Transactional(propagation = Propagation.REQUIRES_NEW)
class BlogController(val blogService: BlogService) {
@GetMapping("/blogs.do")
fun listAll(model: Model): String {
val authentication = SecurityContextHolder.getContext().authentication
model.addAttribute("currentUser", if (authentication == null) null else authentication.principal as UserDetails)
val allblogs = blogService.findAll()
model.addAttribute("blogs", allblogs)
return "jsp/blog/list"
}
@PostMapping("/saveBlog")
@ResponseBody
fun saveBlog(blog: Blog, request: HttpServletRequest):Blog {
blog.author = (request.getSession().getAttribute("currentUser") as UserDetails).username
return blogService.save(blog)
}
@GetMapping("/goEditBlog")
fun goEditBlog(@RequestParam(value = "id") id: String, model: Model): String {
model.addAttribute("blog", blogService.findOne(id))
return "jsp/blog/edit"
}
@PostMapping("/editBlog")
@ResponseBody
fun editBlog(blog: Blog, request: HttpServletRequest) :Blog{
blog.author = (request.getSession().getAttribute("currentUser") as UserDetails).username
blog.gmtModified = Date()
blog.version = blog.version + 1
return blogService.save(blog)
}
@GetMapping("/blog")
fun blogDetail(@RequestParam(value = "id") id: String, model: Model): String {
model.addAttribute("blog", blogService.findOne(id))
return "jsp/blog/detail"
}
@GetMapping("/listblogs")
@ResponseBody
fun listblogs(model: Model) = blogService.findAll()
@GetMapping("/findBlogByTitle")
@ResponseBody
fun findBlogByTitle(@RequestParam(value = "title") title: String) = blogService.findByTitle(title)
}
11.7 前端jsp设计
list.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
<%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions" %>
<!DOCTYPE html>
<html lang="en">
<head>
<jsp:include page="../header.jsp"></jsp:include>
</head>
<body>
<jsp:include page="../top-nav.jsp"></jsp:include>
<div class="col-sm-12">
<h2>文章列表</h2>
<div class="pull-right">
<a href="addBlog" class="btn btn-primary write-btn" target="_blank">写文章</a>
</div>
<table id="blogsTable" class="table table-hover">
<thead>
<tr>
<th>No</th>
<th>Title</th>
<th>Author</th>
<%--<th>Content</th>--%>
<th>CreateTime</th>
</tr>
</thead>
<tbody>
<c:forEach items="${blogs}" var="blog" varStatus="status">
<tr>
<td>${status.index+1}</td>
<td><a href="blog?id=${blog.id}" target="_blank">${blog.title}</a></td>
<td>${blog.author}</td>
<%--<td>${fn: substring(blog.content,0,100)}</td>--%>
<td>${blog.gmtCreated}</td>
</tr>
</c:forEach>
</tbody>
</table>
</div>
<jsp:include page="../copyright.jsp"></jsp:include>
<script data-main="js/views/blog/config" src="js/libs/require/require.js"></script>
<script type="text/javascript">
require(['blog-list-view']);
</script>
</body>
</html>
add.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
<!DOCTYPE html>
<html lang="en">
<head>
<jsp:include page="../header.jsp"></jsp:include>
</head>
<body>
<jsp:include page="../top-nav.jsp"></jsp:include>
<div class="col-sm-10 blog">
<h2>写文章</h2>
<form id="addBlogForm" class="form-horizontal">
<div class="form-group-lg">
<label></label>
<input type="text" name="title" class="form-control" placeholder="文章标题">
</div>
<div class="form-group-lg">
<label></label>
<textarea id="blogContentEditor" type="text" name="content" class="form-control" rows="100"
placeholder=""></textarea>
</div>
<div class="form-group-lg">
<div class="col-sm-offset-2 col-sm-10">
<button type="submit" class="btn btn-primary rest-blog-submit-btn" id="addBlogBtn">保存并发表</button>
</div>
</div>
</form>
</div>
<jsp:include page="../copyright.jsp"></jsp:include>
<script data-main="js/views/blog/config" src="js/libs/require/require.js"></script>
<script type="text/javascript">
require(['blog-add-view']);
</script>
</body>
</html>
detail.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
<!DOCTYPE html>
<html lang="en">
<head>
<jsp:include page="../header.jsp"></jsp:include>
</head>
<body>
<jsp:include page="../top-nav.jsp"></jsp:include>
<div class="container-fluid">
<div class="col-sm-10 blog">
<h1 class="center">${blog.title}</h1>
<input type="hidden" id="blogId" value="${blog.id}">
<div id="goEditBlog" class="btn-link pull-right">编辑</div>
<div class="rest-center">
作者: ${blog.author}
日期: <fmt:formatDate pattern="yyyy/MM/dd HH:mm:ss" value="${blog.gmtModified}"/>
</div>
<textarea id="blogContent" style="display: none"><c:out value="${blog.content}"
escapeXml='false'></c:out></textarea>
<%--<textarea id="blogContent" rows="50" cols="150"><c:out value="${blog.content}" escapeXml='false'></c:out></textarea>--%>
<div class="markdown-body rest-blog-body"></div>
</div>
</div>
<jsp:include page="../copyright.jsp"></jsp:include>
<script data-main="js/views/blog/config" src="js/libs/require/require.js"></script>
<script type="text/javascript">
require(['blog-detail-view']);
</script>
</body>
</html>
edit.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
<!DOCTYPE html>
<html lang="en">
<head>
<jsp:include page="../header.jsp"></jsp:include>
</head>
<body>
<jsp:include page="../top-nav.jsp"></jsp:include>
<div class="col-sm-10 blog">
<h2>写文章</h2>
<form id="editBlogForm" class="form-horizontal">
<input type="hidden" name="id" value="${blog.id}">
<div class="form-group-lg">
<label></label>
<input type="text" name="title" class="form-control" placeholder="文章标题" value="${blog.title}">
</div>
<div class="form-group-lg">
<label></label>
<textarea id="blogContentEditor" type="text" name="content" class="form-control" rows="100"
placeholder=""><c:out value="${blog.content}" escapeXml='false'></c:out></textarea>
</div>
<div class="form-group-lg">
<div class="col-sm-offset-2 col-sm-10">
<button type="submit" class="btn btn-primary rest-blog-submit-btn" id="editBlogBtn">保存并发表</button>
</div>
</div>
</form>
</div>
<jsp:include page="../copyright.jsp"></jsp:include>
<script data-main="js/views/blog/config" src="js/libs/require/require.js"></script>
<script type="text/javascript">
require(['blog-edit-view']);
</script>
</body>
</html>
11.8 前端js代码
我们采用requirejs管理js。
js代码跟html代码隔离。
blog-add-view.js
blog-detail-view.js
blog-edit-view.js
blog-list-view.js
config.js
源代码详见工程:
https://github.com/Jason-Chen-2017/restfeel/tree/master/src/main/resources/static/js/views/blog
11.9 运行效果
系统源代码:https://github.com/Jason-Chen-2017/restfeel/tree/restfeel_blog_md_2017.3.31
小结
我们采用SpringBoot集成mongodb,Java,Kotlin,jsp,jquery,bootstrap,requirejs等技术框架,架构层次分明,快速开发出了一个极简的社区文章博客系统。