Spring Boot內嵌數據庫的使用(H2)


引用 :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如下:

  1.  
    <?xml version="1.0" encoding="UTF-8"?>
  2.  
    <projectxmlns="http://maven.apache.org/POM/4.0.0"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  3.  
    xsi:schemaLocation = "http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd" >
  4.  
    <modelVersion>4.0.0 </modelVersion>
  5.  
     
  6.  
    <groupId>com.springboot </groupId>
  7.  
    <artifactId>demo </artifactId>
  8.  
    <version>0.0.1-SNAPSHOT </version>
  9.  
    <packaging>jar </packaging>
  10.  
     
  11.  
    <name>demo </name>
  12.  
    <description>Demo project for Spring Boot </description>
  13.  
     
  14.  
    <parent>
  15.  
    <groupId>org.springframework.boot </groupId>
  16.  
    <artifactId>spring-boot-starter-parent </artifactId>
  17.  
    <version>1.5.9.RELEASE </version>
  18.  
    <relativePath/> <!-- lookup parent from repository -->
  19.  
    </parent>
  20.  
     
  21.  
    <properties>
  22.  
    <project.build.sourceEncoding>UTF-8 </project.build.sourceEncoding>
  23.  
    <project.reporting.outputEncoding>UTF-8 </project.reporting.outputEncoding>
  24.  
    <java.version>1.8 </java.version>
  25.  
    </properties>
  26.  
     
  27.  
    <dependencies>
  28.  
    <dependency>
  29.  
    <groupId>org.springframework.boot </groupId>
  30.  
    <artifactId>spring-boot-starter-data-jpa </artifactId>
  31.  
    </dependency>
  32.  
     
  33.  
    <dependency>
  34.  
    <groupId>org.springframework.boot </groupId>
  35.  
    <artifactId>spring-boot-starter-thymeleaf </artifactId>
  36.  
    </dependency>
  37.  
     
  38.  
    <dependency>
  39.  
    <groupId>org.springframework.boot </groupId>
  40.  
    <artifactId>spring-boot-starter-web </artifactId>
  41.  
    </dependency>
  42.  
     
  43.  
    <dependency>
  44.  
    <groupId>com.h2database </groupId>
  45.  
    <artifactId>h2 </artifactId>
  46.  
    <scope>runtime </scope>
  47.  
    </dependency>
  48.  
     
  49.  
    <dependency>
  50.  
    <groupId>org.springframework.boot </groupId>
  51.  
    <artifactId>spring-boot-starter-test </artifactId>
  52.  
    <scope>test </scope>
  53.  
    </dependency>
  54.  
    </dependencies>
  55.  
     
  56.  
    <build>
  57.  
    <plugins>
  58.  
    <plugin>
  59.  
    <groupId>org.springframework.boot </groupId>
  60.  
    <artifactId>spring-boot-maven-plugin </artifactId>
  61.  
    </plugin>
  62.  
    </plugins>
  63.  
    </build>
  64.  
    </project>
  • 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,具體詳細信息如下。

  1.  
    package com.springboot.domain;
  2.  
    import java.text.ParseException;
  3.  
    import java.text.SimpleDateFormat;
  4.  
    import java.util.Date;
  5.  
    import javax.persistence.Entity;
  6.  
    import javax.persistence.GeneratedValue;
  7.  
    import javax.persistence.GenerationType;
  8.  
    import javax.persistence.Id;
  9.  
    import javax.persistence.Transient;
  10.  
     
  11.  
    @Entity
  12.  
    public classJournal{
  13.  
    @Id
  14.  
    @GeneratedValue (strategy=GenerationType.AUTO)
  15.  
    private Long id;
  16.  
    private String title;
  17.  
    private Date created;
  18.  
    private String summary;
  19.  
    @Transient
  20.  
    private SimpleDateFormat format = new SimpleDateFormat( "MM/dd/yyyy");
  21.  
    public Journal (String title, String summary, String date) throws ParseException{
  22.  
    this.title = title;
  23.  
    this.summary = summary;
  24.  
    this.created = format.parse(date);
  25.  
    }
  26.  
     
  27.  
    Journal(){}
  28.  
     
  29.  
    public Long getId () {
  30.  
    return id;
  31.  
    }
  32.  
    public void setId (Long id) {
  33.  
    this.id = id;
  34.  
    }
  35.  
    public String getTitle () {
  36.  
    return title;
  37.  
    }
  38.  
    public void setTitle (String title) {
  39.  
    this.title = title;
  40.  
    }
  41.  
    public Date getCreated () {
  42.  
    return created;
  43.  
    }
  44.  
     
  45.  
    public void setCreated (Date created) {
  46.  
    this.created = created;
  47.  
    }
  48.  
     
  49.  
    public String getSummary () {
  50.  
    return summary;
  51.  
    }
  52.  
     
  53.  
    public void setSummary (String summary) {
  54.  
    this.summary = summary;
  55.  
    }
  56.  
     
  57.  
    public String getCreatedAsShort (){
  58.  
    return format.format(created);
  59.  
    }
  60.  
     
  61.  
    public String toString (){
  62.  
    StringBuilder value = new StringBuilder( "JournalEntry(");
  63.  
    value.append( "Id: ");
  64.  
    value.append(id);
  65.  
    value.append( ",Title: ");
  66.  
    value.append(title);
  67.  
    value.append( ",Summary: ");
  68.  
    value.append(summary);
  69.  
    value.append( ",Created: ");
  70.  
    value.append(getCreatedAsShort());
  71.  
    value.append( ")");
  72.  
    return value.toString();
  73.  
    }
  74.  
    }
  • 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接口。代碼如下。

  1.  
    package com.springboot.repository;
  2.  
    import com.springboot.domain.Journal;
  3.  
    import org.springframework.data.jpa.repository.JpaRepository;
  4.  
     
  5.  
    public interfaceJournalRepositoryextendsJpaRepository<Journal,Long> {
  6.  
    }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6

上面的代碼片所展示的是Spring Data Repository JPA技術,要使用這項技術只需要繼承JpaRepository接口即可。JpaRepository是一個標記接口,允許Spring Data Repository引擎識別它並提供必要的代理類來實現基本的CRUD (Create, Read, Update, Delete) 和一些自定義的方法。你可以通過一些類似於findByTitleLike、findBySummary、findByTitleAndSummaryIgnoringCase等等命名約定去實現你的方法。默認情況下,這些方法所實現的功能都會被設置成一個事務。JpaRepository也有一些非常便捷的操作可以對數據進行排序和分頁的操作。

接下來,我們需要創建一個Web controller。

  1.  
    package com .springboot .web ;
  2.  
    import com .springboot .repository .JournalRepository ;
  3.  
    import org .springframework .beans .factory .annotation .Autowired ;
  4.  
    import org .springframework .stereotype .Controller ;
  5.  
    import org .springframework .ui .Model ;
  6.  
    import org .springframework .web .bind .annotation .RequestMapping ;
  7.  
     
  8.  
    @Controller
  9.  
    public class JournalController {
  10.  
    @Autowired
  11.  
    JournalRepository repo ;
  12.  
     
  13.  
    @RequestMapping( "/")
  14.  
    public String index(Model model){
  15.  
    model .addAttribute( "journal", repo .findAll()) ;
  16.  
    return "index" ;
  17.  
    }
  18.  
    }
  • 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文件並寫入如下內容。

  1.  
    <!DOCTYPE html>
  2.  
    <htmllang="en"xmlns:th="http://www.thymeleaf.org">
  3.  
    <head>
  4.  
    <metacharset="utf-8"> </meta>
  5.  
    <metahttp-equiv="Content-Type"content="text/html"> </meta>
  6.  
    <title>Spring Boot Journal </title>
  7.  
    <linkrel="stylesheet"type="text/css"media="all"href="css/bootstrap.min.css"> </link>
  8.  
    </head>
  9.  
    <body>
  10.  
    <h1>Spring Boot Journal </h1>
  11.  
    <ulclass="timeline">
  12.  
    <divth:each="entry,status : ${journal}">
  13.  
    <lith:attr="class=${status.odd}?'timeline-inverted':''">
  14.  
    <divclass="tl-circ"> </div>
  15.  
    <divclass="timeline-panel">
  16.  
    <divclass="tl-heading">
  17.  
    <h4> <spanth:text="${entry.title}">TITLE </span> </h4>
  18.  
    <p> <smallclass="text-muted"> <iclass="glyphicon glyphicon-time"> </i>
  19.  
    <spanth:text="${entry.createdAsShort}">CREATED </span> </small> </p>
  20.  
    </div>
  21.  
    <divclass="tl-body">
  22.  
    <p> <spanth:text="${entry.summary}">SUMMARY </span> </p>
  23.  
    </div>
  24.  
    </div>
  25.  
    </li>
  26.  
    </div>
  27.  
    </ul>
  28.  
    </body>
  29.  
    </html>
  • 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去下載。

現在,就剩下最重要的一步,構建數據和實現應用入口。代碼如下;

  1.  
    package com .springboot ;
  2.  
     
  3.  
    import com .springboot .domain .Journal ;
  4.  
    import com .springboot .repository .JournalRepository ;
  5.  
    import org .springframework .beans .factory .InitializingBean ;
  6.  
    import org .springframework .boot .SpringApplication ;
  7.  
    import org .springframework .boot .autoconfigure .SpringBootApplication ;
  8.  
    import org .springframework .context .annotation .Bean ;
  9.  
     
  10.  
    @SpringBootApplication
  11.  
    public class DemoApplication {
  12.  
     
  13.  
    @Bean
  14.  
    InitializingBean saveData(JournalRepository repo){
  15.  
    return ()->{
  16.  
    repo .save( new Journal( "Get to know Spring Boot", "Today I will learn Spring Boot", "01/01/2016")) ;
  17.  
    repo .save( new Journal( "Simple Spring Boot Project", "I will do my first Spring Boot Project", "01/02/2016")) ;
  18.  
    repo .save( new Journal( "Spring Boot Reading", "Read more about Spring Boot", "02/01/2016")) ;
  19.  
    repo .save( new Journal( "Spring Boot in the Cloud", "Spring Boot using Cloud Foundry", "03/01/2016")) ;
  20.  
    } ;
  21.  
    }
  22.  
     
  23.  
    public static void main(String[] args) {
  24.  
    SpringApplication .run(DemoApplication .class, args) ;
  25.  
    }
  26.  
    }
  • 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,如果程序不出錯,將會出現如下的結果; 
這里寫圖片描述


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM