《Springboot极简教程》 第11章 Springboot集成mongodb开发小结

第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 系统架构设计

领域模型

Blog

前后端分层

后端Controller

jsp

js

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等技术框架,架构层次分明,快速开发出了一个极简的社区文章博客系统。

参考资料: 1.http://baike.baidu.com/item/mongodb

本文参与腾讯云自媒体分享计划,欢迎正在阅读的你也加入,一起分享。

发表于

我来说两句

0 条评论
登录 后参与评论

相关文章

来自专栏Hongten

apache的开源项目-模板引擎(Velocity)_学习了两天就上手啦_源码下载

首先,如果你对Velocity不是很了解,还是建议你去apache的官方网站上去走走....

18810
来自专栏技术小黑屋

Android中一个简单有用的发现性能问题的方法

在Android中,性能优化是我们持之不懈的工作。这其中,在主线程执行耗时的任务,可能会导致界面卡顿,甚至是ANR(程序未响应)。当然Android提供了很多优...

10610
来自专栏算法修养

PAT 甲级 1025 PAT Ranking

1025. PAT Ranking (25) 时间限制 200 ms 内存限制 65536 kB 代码长度限制 16000 B 判题...

333100
来自专栏Java与Android技术栈

使用 Kotlin + Spring Boot 进行后端开发Kotlin示例一:结合 Redis 进行数据存储和查询示例二:结合 RxJava 模拟顺序、并发地执行任务总结

Kotlin 是一个基于 JVM 的编程语言,它的简洁、便利早已不言而喻。Kotlin 能够胜任 Java 做的所有事。目前,我们公司 C 端 的 Androi...

18530
来自专栏一枝花算不算浪漫

SpringBoot自定义序列化的使用方式--WebMvcConfigurationSupport

21110
来自专栏码匠的流水账

聊聊resilience4j的CircuitBreakerConfig

本文主要研究一下resilience4j的CircuitBreakerConfig

38120
来自专栏java、Spring、技术分享

Spring Import 三种用法与源码解读

  最近在看Spring Cloud相关的源码,每次引入一个新的starter,发现都会加一些enable的注解,比如:@EnableDiscoveryClie...

50140
来自专栏技术记录

rabbitMQ教程(三) spring整合rabbitMQ代码实例

一、开启rabbitMQ服务,导入MQ jar包和gson jar包(MQ默认的是jackson,但是效率不如Gson,所以我们用gson) ? ?  二、发...

37380
来自专栏IT 指南者专栏

Spring 框架系列之 JDBC 整合

微信公众号:compassblog 欢迎关注、转发,互相学习,共同进步! 有任何问题,请后台留言联系! 1、Spring框架整合 DAO 模板 JDBC:org...

346110
来自专栏技术专栏

logback日志写入kafka遇到的那些坑

这两天在学习storm实时流的时候需要将logback日志写入kafka,这期间遇到了很多坑,这里把遇到的坑和解决的问题记录一下,和大家共勉

2.2K30

扫码关注云+社区

领取腾讯云代金券