h2數據庫作為內存型與springboot+mybatis的案例


  • 一.前言

    H2 是一個用 Java 開發的嵌入式數據庫,它本身只是一個類庫,即只有一個 jar 文件,可以直接嵌入到應用項目中。H2 主要有如下三個用途:

    第一個用途,也是最常使用的用途就在於可以同應用程序打包在一起發布,這樣可以非常方便地存儲少量結構化數據。

    第二個用途是用於單元測試。啟動速度快,而且可以關閉持久化功能,每一個用例執行完隨即還原到初始狀態。

    第三個用途是作為緩存,即當做內存數據庫,作為NoSQL的一個補充。當某些場景下數據模型必須為關系型,可以拿它當Memcached使,作為后端MySQL/Oracle的一個緩沖層,緩存一些不經常變化但需要頻繁訪問的數據,比如字典表、權限表。
    H2 可以作為:
    1)嵌入式模式(使用 JDBC 的本地連接)
    2)服務器模式(使用 JDBC 或 ODBC 在 TCP/IP 上的遠程連接)
    3)混合模式(本地和遠程連接同時進行)
    該案例為嵌入式模式

    二.springboot創建項目

    首先,給大家看一下我的項目結構

    springboot的版本為:2.1.9 具體可以看一下我的pom文件

    2.1 依賴pom文件

    以下就是我該演示項目的所有依賴,h2的版本交給springboot去進行確定

    <properties>
            <java.version>1.8</java.version>
        </properties>
    
        <dependencies>
            <!--starter-web-->
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-web</artifactId>
            </dependency>
            <!--連接H2的mybatis-->
            <dependency>
                <groupId>org.mybatis.spring.boot</groupId>
                <artifactId>mybatis-spring-boot-starter</artifactId>
                <version>2.1.1</version>
            </dependency>
            <!--h2數據庫-->
            <dependency>
                <groupId>com.h2database</groupId>
                <artifactId>h2</artifactId>
                <scope>runtime</scope>
            </dependency>
            <dependency>
                <groupId>org.projectlombok</groupId>
                <artifactId>lombok</artifactId>
                <optional>true</optional>
            </dependency>
            <!--測試-->
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-test</artifactId>
                <scope>test</scope>
            </dependency>
        </dependencies>
    
        <build>
            <plugins>
                <plugin>
                    <groupId>org.springframework.boot</groupId>
                    <artifactId>spring-boot-maven-plugin</artifactId>
                </plugin>
            </plugins>
            <!--把放置在mapper路徑下的xml文件編譯后放在一起-->
            <resources>
                <resource>
                    <directory>src/main/java</directory>
                    <includes>
                        <include>**/*.xml</include>
                    </includes>
                    <filtering>true</filtering>
                </resource>
            </resources>
        </build>

    2.2 application.yml

    需要關注 h2 web操作界面的路徑 和 console打印的sql語句,以下的配置是本文精華部分

    spring:
      h2:
        console:
          path: /h2-console #進入h2 web操作界面的路徑
          enabled: true #開啟h2 web界面
      datasource:
        driver-class-name: org.h2.Driver
        schema: classpath:db/schema-h2.sql
        data: classpath:db/data-h2.sql
        url: jdbc:h2:mem:test
        username: root
        password: test
    
    mybatis:
      configuration:
        log-impl: org.apache.ibatis.logging.stdout.StdOutImpl # 在console打印sql語句
    
    server:
      port: 8081

    2.3 sql語句

    data-h2.sql,需要放置在resource/db下
    INSERT INTO cat (id, name, age, color,score) VALUES
    (1, 'Jone', 18, '黃色',0.4),
    (2, 'Jack', 20, '白色',0.5),
    (3, 'Tom', 28, '金色',0.1),
    (4, 'Sandy', 21, '紅色',0.8),
    (5, 'Billie', 24, '綠色',0.7);
    schema-h2.sql,需要放置在resource/db下
    DROP TABLE IF EXISTS cat;
    
    CREATE TABLE cat
    (
        id BIGINT(20) NOT NULL COMMENT '主鍵ID',
        name VARCHAR(30) NULL DEFAULT NULL COMMENT '姓名',
        age INT(11) NULL DEFAULT NULL COMMENT '年齡',
        color VARCHAR(50) NULL DEFAULT NULL COMMENT '顏色',
        score DOUBLE NULL DEFAULT NULL COMMENT '分數',
        PRIMARY KEY (id)
    );

    2.4 啟動類上配上mapper掃描

    /**
     * @author CC-CAN
     */
    @SpringBootApplication
    @MapperScan("com.springboot.*.mapper")
    public class MybatisApplication {
    
        public static void main(String[] args) {
            SpringApplication.run(MybatisApplication.class, args);
        }
    
    }

    2.5 mapper.java和mapper.xml

    配置后,由mybatis進行實體類的映射

    public interface CatMapper {
    
        List<Cat> selectAll();
    
    }
    <?xml version="1.0" encoding="UTF-8"?>
    <!DOCTYPE mapper
            PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
            "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
    <mapper namespace="com.springboot.mybatis.mapper.CatMapper">
        <select id="selectAll" resultType="com.springboot.mybatis.entity.Cat">
            SELECT * from cat
        </select>
    </mapper>

    2.6 案例的entity

    與數據庫的實體對應

    @Data
    public class Cat {
        private Long id;
        private String name;
        private Integer age;
        private String color;
        private Double score;
    }

    2.7 service 和 impl

    public interface CatService {
    
        /**
         * 喵叫
         * @return
         */
        String meow();
    
        List<Cat> list();
    
    }
    @Service
    public class CatServiceImpl implements CatService {
    
        @Autowired
        private CatMapper catMapper;
    
        @Override
        public String meow() {
            return "瞄";
        }
    
        @Override
        public List<Cat> list() {
            return catMapper.selectAll();
        }
    }

    2.8 建立測試類

    在test創建 springboot 的測試類
    @RunWith(SpringRunner.class)
    @SpringBootTest
    public class MybatisApplicationTests {
    
        @Autowired
        private CatService catService;
    
        @Test
        public void contextLoads() {
            List<Cat> list = catService.list();
            list.forEach(System.out::println);
        }
    
    }

    三 測試結果

    Creating a new SqlSession
    SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@6caf7803] was not registered for synchronization because synchronization is not active
    JDBC Connection [HikariProxyConnection@408543908 wrapping conn0: url=jdbc:h2:mem:test user=ROOT] will not be managed by Spring
    ==>  Preparing: SELECT * from cat 
    ==> Parameters: 
    <==    Columns: ID, NAME, AGE, COLOR, SCORE
    <==        Row: 1, Jone, 18, 黃色, 0.4
    <==        Row: 2, Jack, 20, 白色, 0.5
    <==        Row: 3, Tom, 28, 金色, 0.1
    <==        Row: 4, Sandy, 21, 紅色, 0.8
    <==        Row: 5, Billie, 24, 綠色, 0.7
    <==      Total: 5
    Closing non transactional SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@6caf7803]
    Cat(id=1, name=Jone, age=18, color=黃色, score=0.4)
    Cat(id=2, name=Jack, age=20, color=白色, score=0.5)
    Cat(id=3, name=Tom, age=28, color=金色, score=0.1)
    Cat(id=4, name=Sandy, age=21, color=紅色, score=0.8)
    Cat(id=5, name=Billie, age=24, color=綠色, score=0.7)

    四 打開h2的web瀏覽頁面

    運行main方法

    瀏覽器輸入 

    http://localhost:8081/h2-console

    賬號 root 密碼 test,進去

    查看

    結語

    本人長期從事java開發,如果有什么疑問,可以留言,我會及時解答

    附錄


免責聲明!

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



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