Spring Data JPA(二):SpringBoot集成H2

H2是Thomas Mueller提供的一個開源的、純java實現(xiàn)的關(guān)系數(shù)據(jù)庫。

前言

本篇文章引導(dǎo)你使用Spring Boot,Spring Data JPA集成H2內(nèi)存數(shù)據(jù)庫。更多關(guān)于H2數(shù)據(jù)參考:http://www.h2database.com/html/tutorial.html

準(zhǔn)備

  • JDK 1.8 或更高版本
  • Maven 3 或更高版本

技術(shù)棧

  • Spring Data JPA
  • Spring Boot

目錄結(jié)構(gòu)

pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="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">
    <parent>
        <artifactId>jpa-example</artifactId>
        <groupId>cn.merryyou</groupId>
        <version>1.0-SNAPSHOT</version>
    </parent>
    <modelVersion>4.0.0</modelVersion>

    <artifactId>h2-webconsole</artifactId>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>

        <dependency>
            <groupId>com.h2database</groupId>
            <artifactId>h2</artifactId>
            <version>1.4.196</version>
        </dependency>

        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.6.1</version>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                </configuration>
            </plugin>
        </plugins>
    </build>

</project>

實體類

User
@Entity
@Table(name = "t_user")
@Data
public class User {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    private String name;

    private String url;

    @Override
    public String toString() {
        return "User{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", url='" + url + '\'' +
                '}';
    }
}
  • @Table聲明此對象映射到數(shù)據(jù)庫的數(shù)據(jù)表,通過它可以為實體指定表(talbe),目錄(Catalog)和schema的名字。該注釋不是必須的,如果沒有則系統(tǒng)使用默認(rèn)值(實體的短類名)。

  • @Id 聲明此屬性為主鍵。該屬性值可以通過應(yīng)該自身創(chuàng)建,但是Hibernate推薦通過Hibernate生成

  • @GeneratedValue 指定主鍵的生成策略。

    1. TABLE:使用表保存id值
    2. IDENTITY:identitycolumn
    3. SEQUENCR :sequence
    4. AUTO:根據(jù)數(shù)據(jù)庫的不同使用上面三個
  • @Column 聲明該屬性與數(shù)據(jù)庫字段的映射關(guān)系。

AddressRepository
public interface UserRepository extends JpaRepository<User, Integer> {
}

Spring Data JPA包含了一些內(nèi)置的Repository,實現(xiàn)了一些常用的方法:findone,findall,save等。

application.yml
spring:
  datasource:
    url: jdbc:h2:mem:h2test;DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=FALSE
    platform: h2
    username: sa
    password:
    driverClassName: org.h2.Driver
  jpa:
    database-platform: org.hibernate.dialect.H2Dialect
    hibernate:
      ddl-auto: update
    properties:
      hibernate:
        show_sql: true
        use_sql_comments: true
        format_sql: true
  h2:
    console:
      enabled: true
      path: /console
      settings:
        trace: false
        web-allow-others: false
logging:
  level: debug
連接配置

application.yml文件中對數(shù)據(jù)庫進(jìn)行連接配置

  • spring.datasource.url=jdbc:h2:mem:h2test,配置h2數(shù)據(jù)庫的連接地址
  • spring.datasource.driver-class-name=org.h2.Driver,配置JDBC Driver
  • spring.datasource.username=sa,配置數(shù)據(jù)庫用戶名
  • spring.datasource.password=,配置數(shù)據(jù)庫密碼

當(dāng)你完成依賴和連接配置這兩步之后,你就可以在程序種使用h2了。spring會自動幫你完成DataSource的注入。

數(shù)據(jù)初始化配置

如果你需要在程序啟動時對數(shù)據(jù)庫進(jìn)行初始化操作,則在application.properties文件中對數(shù)據(jù)庫進(jìn)接配置

  • spring.datasource.schema=classpath:db/schema.sql,進(jìn)行該配置后,每次啟動程序,程序都會運行resources/db/schema.sql文件,對數(shù)據(jù)庫的結(jié)構(gòu)進(jìn)行操作。
  • spring.datasource.data=classpath:db/data.sql,進(jìn)行該配置后,每次啟動程序,程序都會運行resources/db/data.sql文件,對數(shù)據(jù)庫的數(shù)據(jù)操作。

該配置非常適合開發(fā)環(huán)境,我會把數(shù)據(jù)庫的結(jié)構(gòu)構(gòu)建sql放在resources/db/schema.sql,數(shù)據(jù)sql放在resources/db/data.sql中。這樣每次運行程序我都可以得到一個新的數(shù)據(jù)庫。這樣就不需要我每次為了測試而修改數(shù)據(jù)中的內(nèi)容了。

h2 web consloe配置

h2 web consloe是一個數(shù)據(jù)庫GUI管理應(yīng)用,就和phpMyAdmin類似。程序運行時,會自動啟動h2 web consloe。當(dāng)然你也可以進(jìn)行如下的配置。

  • spring.h2.console.settings.web-allow-others=true,進(jìn)行該配置后,h2 web consloe就可以在遠(yuǎn)程訪問了。否則只能在本機(jī)訪問。
  • spring.h2.console.path=/h2-console,進(jìn)行該配置,你就可以通過YOUR_URL/h2-console訪問h2 web consloeYOUR_URL是你程序的訪問URl。
  • spring.h2.console.enabled=true,進(jìn)行該配置,程序開啟時就會啟動h2 web consloe。當(dāng)然這是默認(rèn)的,如果你不想在啟動程序時啟動h2 web consloe,那么就設(shè)置為false。
UserRepositoryTest
@SpringBootTest
@RunWith(SpringRunner.class)
@Slf4j
public class UserRepositoryTest {

    @Autowired
    private UserRepository userRepository;

    @Test
    public void saveTest() throws Exception {
        User user = new User();
        user.setName("鄭龍飛");
        user.setUrl("http://merryyou.cn");
        User result = userRepository.save(user);
        log.info(result.toString());
        Assert.assertNotNull(user.getId());
    }

    @Test
    public void findOneTest() throws Exception{
        User user = userRepository.findOne(1l);
        log.info(user.toString());
        Assert.assertNotNull(user);
        Assert.assertTrue(1l==user.getId());
    }
}
h2 web consloe

代碼下載

從我的 github 中下載,https://github.com/longfeizheng/jpa-example/tree/master/h2-webconsole


??????關(guān)注微信小程序java架構(gòu)師歷程
上下班的路上無聊嗎?還在看小說、新聞嗎?不知道怎樣提高自己的技術(shù)嗎?來吧這里有你需要的java架構(gòu)文章,1.5w+的java工程師都在看,你還在等什么?

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • Spring Boot 參考指南 介紹 轉(zhuǎn)載自:https://www.gitbook.com/book/qbgb...
    毛宇鵬閱讀 47,275評論 6 342
  • Spring Cloud為開發(fā)人員提供了快速構(gòu)建分布式系統(tǒng)中一些常見模式的工具(例如配置管理,服務(wù)發(fā)現(xiàn),斷路器,智...
    卡卡羅2017閱讀 136,603評論 19 139
  • 要加“m”說明是MB,否則就是KB了. -Xms:初始值 -Xmx:最大值 -Xmn:最小值 java -Xms8...
    dadong0505閱讀 5,070評論 0 53
  • application的配置屬性。 這些屬性是否生效取決于對應(yīng)的組件是否聲明為Spring應(yīng)用程序上下文里的Bea...
    新簽名閱讀 5,540評論 1 27
  • 轉(zhuǎn)眼間,大家都已各奔東西。這個世界總是以各種各樣的方式給予你懲罰,像是在贖罪一般。 縱觀生活,起起落落,前一秒或許...
    糯米真的超好吃閱讀 329評論 0 0

友情鏈接更多精彩內(nèi)容