引用 :https://blog.csdn.net/justlpf/article/details/80269146
Thyemleaf介紹: https://www.cnblogs.com/wotoufahaiduo/p/11178629.html
Spring FrameWork提供對於SQL數據庫提供了非常廣泛的支持,從直接使用JdbcTemplate的JDBC到類似Hibernate等完備的ORM技術。Spring Data提供一個額外的功能, 直接從接口創建Repository實現, 並使用約定從你的方法名生成查詢。
配置數據源(DataSource)
Java的javax.sql.DataSource接口提供了一個標准的使用數據庫連接的方法。 傳統做法是, 一個DataSource使用一個URL以及相應的證書去構建一個數據庫連接。
內嵌數據庫的支持
在開發應用的過程中使用內嵌的內存數據庫是非常方便的,很明顯,內存數據庫不提供數據的持久化存儲;當應用啟動時你需要填充你的數據庫,當應用結束時數據將會丟棄。
Spring Boot可以自動的配置內嵌的H2、HSQL、Derby數據庫。你不需要提供任何鏈接URLs,只需要簡單的提供一個你需要使用的內嵌數據庫的依賴即可。
如果在測試時要使用內嵌數據庫的功能,需要注意在默認情況下無論使用多少個應用上下文在整個測試過程中相同的數據庫都是可用復用的。如果想要讓每個應用上下文使用隔離的內嵌數據庫,應該設置spring.datasource.generate-unique-name為ture。
內嵌數據庫的使用
本文通過演示H2內嵌數據庫的使用來幫助理解在Spring Boot中如何使用內嵌數據庫。
要使用H2內嵌數據庫,首先需要添加JPA和H2的依賴,但是我們從數據庫讀取數據之后,需要展示在頁面上,所以需要配置一個模板引擎,本文選擇thymeleaf作為我們應用的模板引擎,所以也需要添加對thymeleaf的依賴。
添加之后的pom.xml如下:
-
<?xml version="1.0" encoding="UTF-8"?>
-
<projectxmlns="http://maven.apache.org/POM/4.0.0"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
-
xsi:schemaLocation
=
"http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"
>
-
<modelVersion>4.0.0
</modelVersion>
-
-
<groupId>com.springboot
</groupId>
-
<artifactId>demo
</artifactId>
-
<version>0.0.1-SNAPSHOT
</version>
-
<packaging>jar
</packaging>
-
-
-
<description>Demo project for Spring Boot
</description>
-
-
-
<groupId>org.springframework.boot
</groupId>
-
<artifactId>spring-boot-starter-parent
</artifactId>
-
<version>1.5.9.RELEASE
</version>
-
-
-
-
-
<project.build.sourceEncoding>UTF-8
</project.build.sourceEncoding>
-
<project.reporting.outputEncoding>UTF-8
</project.reporting.outputEncoding>
-
<java.version>1.8
</java.version>
-
-
-
-
-
<groupId>org.springframework.boot
</groupId>
-
<artifactId>spring-boot-starter-data-jpa
</artifactId>
-
-
-
-
<groupId>org.springframework.boot
</groupId>
-
<artifactId>spring-boot-starter-thymeleaf
</artifactId>
-
-
-
-
<groupId>org.springframework.boot
</groupId>
-
<artifactId>spring-boot-starter-web
</artifactId>
-
-
-
-
<groupId>com.h2database
</groupId>
-
<artifactId>h2
</artifactId>
-
-
-
-
-
<groupId>org.springframework.boot
</groupId>
-
<artifactId>spring-boot-starter-test
</artifactId>
-
-
-
-
-
-
-
-
<groupId>org.springframework.boot
</groupId>
-
<artifactId>spring-boot-maven-plugin
</artifactId>
-
-
-
-
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
- 40
- 41
- 42
- 43
- 44
- 45
- 46
- 47
- 48
- 49
- 50
- 51
- 52
- 53
- 54
- 55
- 56
- 57
- 58
- 59
- 60
- 61
- 62
- 63
- 64
對於我們的示例程序來說,我們需要創建一個實體類,類名我們將其命名為Journal,具體詳細信息如下。
-
package com.springboot.domain;
-
import java.text.ParseException;
-
import java.text.SimpleDateFormat;
-
-
import javax.persistence.Entity;
-
import javax.persistence.GeneratedValue;
-
import javax.persistence.GenerationType;
-
import javax.persistence.Id;
-
import javax.persistence.Transient;
-
-
-
-
-
@GeneratedValue
(strategy=GenerationType.AUTO)
-
-
-
-
-
-
private SimpleDateFormat format =
new SimpleDateFormat(
"MM/dd/yyyy");
-
public
Journal
(String title, String summary, String date)
throws
ParseException{
-
-
-
this.created = format.parse(date);
-
-
-
-
-
-
-
-
public
void
setId
(Long id) {
-
-
-
public
String
getTitle
() {
-
-
-
public
void
setTitle
(String title) {
-
-
-
public
Date
getCreated
() {
-
-
-
-
public
void
setCreated
(Date created) {
-
-
-
-
public
String
getSummary
() {
-
-
-
-
public
void
setSummary
(String summary) {
-
-
-
-
public
String
getCreatedAsShort
(){
-
return format.format(created);
-
-
-
public
String
toString
(){
-
StringBuilder value =
new StringBuilder(
"JournalEntry(");
-
-
-
value.append(
",Title: ");
-
-
value.append(
",Summary: ");
-
-
value.append(
",Created: ");
-
value.append(getCreatedAsShort());
-
-
-
-
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
- 40
- 41
- 42
- 43
- 44
- 45
- 46
- 47
- 48
- 49
- 50
- 51
- 52
- 53
- 54
- 55
- 56
- 57
- 58
- 59
- 60
- 61
- 62
- 63
- 64
- 65
- 66
- 67
- 68
- 69
- 70
- 71
- 72
- 73
- 74
在上面的代碼片段中,因為使用了JPA技術,所以你需要使用@Entity, @Id和@GeneratedValue注解,因此這個類被標記作為JPA實體並且能夠被持久化到數據庫中。你也可以看到,在我們的代碼中也使用了@Transient注解,這個注解表示JPA引擎不會持久化被注解的屬性,因為上面的代碼片中被@Transient注解的屬性僅僅只是用來格式化日期。這個類有兩個構造函數,一個沒有參數,JPA引擎需要這個構造函數,另外一個構造函數需要用來填充數據庫的參數。
我們覆蓋(override)了一個toString方法,主要用來打印記錄。
接下來,我們需要為數據創建一個持久化機制,那么我們就需要使用Spring Data JPA技術了,創建一個接口,繼承JpaRepository接口。代碼如下。
-
package com.springboot.repository;
-
import com.springboot.domain.Journal;
-
import org.springframework.data.jpa.repository.JpaRepository;
-
-
public
interfaceJournalRepositoryextendsJpaRepository<Journal,Long> {
-
上面的代碼片所展示的是Spring Data Repository JPA技術,要使用這項技術只需要繼承JpaRepository接口即可。JpaRepository是一個標記接口,允許Spring Data Repository引擎識別它並提供必要的代理類來實現基本的CRUD (Create, Read, Update, Delete) 和一些自定義的方法。你可以通過一些類似於findByTitleLike、findBySummary、findByTitleAndSummaryIgnoringCase等等命名約定去實現你的方法。默認情況下,這些方法所實現的功能都會被設置成一個事務。JpaRepository也有一些非常便捷的操作可以對數據進行排序和分頁的操作。
接下來,我們需要創建一個Web controller。
-
package
com
.springboot
.web
-
import
com
.springboot
.repository
.JournalRepository
-
import
org
.springframework
.beans
.factory
.annotation
.Autowired
-
import
org
.springframework
.stereotype
.Controller
-
import
org
.springframework
.ui
.Model
-
import
org
.springframework
.web
.bind
.annotation
.RequestMapping
-
-
-
public class JournalController {
-
-
-
-
-
public String index(Model model){
-
model
.addAttribute(
"journal",
repo
.findAll())
-
-
-
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
@Controller注解、@Autowired注解、@RequestMapping注解我們不在詳細介紹,如果使用過Spring MVC開發過應用,這些注解基本都已經了如指掌。在我們的index方法中,有一個Model類的參數,他用來添加一個名為journal的屬性值,該屬性的值通過調用JournalRepository接口repo.findAll() 獲取。JournalRepository繼承自JpaRepository,所以該接口有很多不同的默認方法,findAll方法就是其中之一。該方法返回數據庫中所有的實體。
接下來我們需要構建模板文件,在src/main/resources/templates目錄下,需要創建一個index.html文件並寫入如下內容。
-
-
<htmllang="en"xmlns:th="http://www.thymeleaf.org">
-
-
<metacharset="utf-8">
</meta>
-
<metahttp-equiv="Content-Type"content="text/html">
</meta>
-
<title>Spring Boot Journal
</title>
-
<linkrel="stylesheet"type="text/css"media="all"href="css/bootstrap.min.css">
</link>
-
-
-
<h1>Spring Boot Journal
</h1>
-
-
<divth:each="entry,status : ${journal}">
-
<lith:attr="class=${status.odd}?'timeline-inverted':''">
-
<divclass="tl-circ">
</div>
-
<divclass="timeline-panel">
-
-
<h4>
<spanth:text="${entry.title}">TITLE
</span>
</h4>
-
<p>
<smallclass="text-muted">
<iclass="glyphicon glyphicon-time">
</i>
-
<spanth:text="${entry.createdAsShort}">CREATED
</span>
</small>
</p>
-
-
-
<p>
<spanth:text="${entry.summary}">SUMMARY
</span>
</p>
-
-
-
-
-
-
-
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
注意:在static目錄下新建一個css目錄,添加bootstrap.min.css文件,該文件自行到bootstrap去下載。
現在,就剩下最重要的一步,構建數據和實現應用入口。代碼如下;
-
-
-
import
com
.springboot
.domain
.Journal
-
import
com
.springboot
.repository
.JournalRepository
-
import org
.springframework
.beans
.factory
.InitializingBean
-
import org
.springframework
.boot
.SpringApplication
-
import org
.springframework
.boot
.autoconfigure
.SpringBootApplication
-
import org
.springframework
.context
.annotation
.Bean
-
-
-
public
class DemoApplication {
-
-
-
InitializingBean saveData(JournalRepository repo){
-
-
repo
.save(
new Journal(
"Get to know Spring Boot",
"Today I will learn Spring Boot",
"01/01/2016"))
-
repo
.save(
new Journal(
"Simple Spring Boot Project",
"I will do my first Spring Boot Project",
"01/02/2016"))
-
repo
.save(
new Journal(
"Spring Boot Reading",
"Read more about Spring Boot",
"02/01/2016"))
-
repo
.save(
new Journal(
"Spring Boot in the Cloud",
"Spring Boot using Cloud Foundry",
"03/01/2016"))
-
-
-
-
public static void main(String[] args) {
-
SpringApplication
.run(DemoApplication
.class, args)
-
-
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
注意:這里要提及的一點就是saveData方法返回的是一個InitializingBean,這個特殊的類在Spring引擎創建序列化實例時會被調用。在本示例中,這個方法將會在應用完成運行的過程中被執行。
以上基本所有工作已經完成,點擊Intellij IDEA的運行按鈕運行應用,應用運行成功之后在瀏覽器輸入http://localhost:8080,如果程序不出錯,將會出現如下的結果;
