• SpringBoot笔记:SpringBoot集成MybatisPlus、H2纯内存数据库实战


    前言

        有一些使用场景比较简单不需要搭建 mysql 等比较重型的服务,使用小而轻巧的内存数据库也能满足要求,本文将实战操作纯内存型数据库 H2。

    H2 数据库特性:

    • 非常快、开源、支持 JDBC AP
    • 嵌入式和服务式模式,内存型数据库
    • 基于浏览器控制台的应用程序,不需要安装第三方工具
    • 占用空间小,jar 仅仅只有 2MB 大小

    下面是 H2 和其他数据库之间的对比:
    对比图

    实战演练

    代码结构

    整合h2

    pom.xml 配置

    
    <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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
        <modelVersion>4.0.0modelVersion>
        <parent>
            <groupId>org.examplegroupId>
            <artifactId>springboot-learning-parentsartifactId>
            <version>1.0-SNAPSHOTversion>
        parent>
    
        <groupId>springboot-demogroupId>
        <artifactId>springboot-h2artifactId>
        <version>1.0-SNAPSHOTversion>
        <name>springboot-h2name>
        <url>https://gitee.com/leo825/springboot-learning-parents.giturl>
        <description>springboot集成h2纯内存型数据库description>
        <properties>
            <start-class>com.demo.SpringbootH2Applicationstart-class>
            <project.build.sourceEncoding>UTF-8project.build.sourceEncoding>
            <project.reporting.outputEncoding>UTF-8project.reporting.outputEncoding>
            <java.version>1.8java.version>
            <mybatisplus.version>3.5.1mybatisplus.version>
            <freemaker.version>2.3.31freemaker.version>
            <mysql.version>8.0.28mysql.version>
        properties>
        <dependencies>
            <dependency>
                <groupId>org.springframework.bootgroupId>
                <artifactId>spring-boot-devtoolsartifactId>
            dependency>
    
            <dependency>
                <groupId>org.springframework.bootgroupId>
                <artifactId>spring-boot-starter-webartifactId>
            dependency>
            <dependency>
                <groupId>org.springframework.bootgroupId>
                <artifactId>spring-boot-starter-testartifactId>
                <scope>testscope>
            dependency>
            <dependency>
                <groupId>org.projectlombokgroupId>
                <artifactId>lombokartifactId>
            dependency>
    
            
            <dependency>
                <groupId>com.baomidougroupId>
                <artifactId>mybatis-plus-boot-starterartifactId>
                <version>${mybatisplus.version}version>
            dependency>
            <dependency>
                <groupId>com.baomidougroupId>
                <artifactId>mybatis-plus-generatorartifactId>
                <version>${mybatisplus.version}version>
            dependency>
            <dependency>
                <groupId>org.freemarkergroupId>
                <artifactId>freemarkerartifactId>
                <version>2.3.31version>
            dependency>
    
            
            <dependency>
                <groupId>com.h2databasegroupId>
                <artifactId>h2artifactId>
            dependency>
        dependencies>
    
        <build>
            <plugins>
                <plugin>
                    <groupId>org.springframework.bootgroupId>
                    <artifactId>spring-boot-maven-pluginartifactId>
                plugin>
            plugins>
        build>
    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
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 71
    • 72
    • 73
    • 74
    • 75
    • 76
    • 77
    • 78

    application.yml 配置

    #端口,项目上下文
    server:
      port: 8080
      servlet:
        context-path: /springboot-h2
    
    spring:
      datasource:
        username: leo825
        password: 1WSX@357wj
        # 如果需要数据本地化,则改成 file 方式
        # jdbc:h2:file:D:/program/sqlite3/db/testDB;AUTO_SERVER=TRUE;DB_CLOSE_DELAY=-1
        url: jdbc:h2:mem:testDB;DB_CLOSE_DELAY=-1
        driver-class-name: org.h2.Driver
        # 初始化表
        schema: classpath:schema.sql
        # 初始化数据
        data: classpath:data.sql
        initialization-mode: always
        continue-on-error: true
        # 开启这个配置就可以通过 web 页面访问了,例如:http://localhost:8080/springboot-h2/h2-console
        h2:
          console:
            enabled: true
            settings:
              # 开启h2 console 跟踪 方便调试  默认 false
              trace: true
              # 允许console 远程访问 默认false
              web-allow-others: true
              # h2 访问路径上下文
              path: /h2-console
    
    
    # mybatis-plus 配置
    mybatis-plus:
      mapper-locations: classpath*:/mapper/**/*.xml
      #实体扫描,多个package用逗号或者分号分隔
      typeAliasesPackage: com.dmo.entity
      global-config:
        #数据库相关配置
        db-config:
          #主键类型  AUTO:"数据库ID自增", INPUT:"用户输入ID", ID_WORKER:"全局唯一ID (数字类型唯一ID)", UUID:"全局唯一ID UUID";
          id-type: AUTO
          #字段策略 IGNORED:"忽略判断",NOT_NULL:"非 NULL 判断"),NOT_EMPTY:"非空判断"
          field-strategy: NOT_NULL
          #驼峰下划线转换
          column-underline: true
          logic-delete-value: -1
          logic-not-delete-value: 0
        banner: false
      #原生配置
      configuration:
        # 打印sql
        log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
        map-underscore-to-camel-case: true
        cache-enabled: false
        call-setters-on-nulls: true
        jdbc-type-for-null: 'null'
    
    # 日志输出配置
    logging:
      level:
        root: INFO
        org:
          springframework:
            security: WARN
            web: ERROR
      file:
        path: ./logs
        name: './logs/springboot-sqlite.log'
      pattern:
        file: '%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{50}:%L - %msg%n'
        console: '%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{50}:%L - %msg%n'
    
    • 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

    data.sql

    insert into t_user(id, username, pwd, create_time, update_time) values (0,'zhhangsan','1222', {ts '2022-07-27 18:47:52.69'}, {ts '2022-07-27 18:47:52.69'})
    
    • 1

    base

    Result.java

    package com.demo.base;
    
    public class Result<T> {
        private Integer code;
        private String msg;
        private String message;
        private T data;
    
    
        public Integer getCode() {
            return code;
        }
    
        public void setCode(Integer code) {
            this.code = code;
        }
    
        public String getMsg() {
            return msg;
        }
    
        public void setMsg(String msg) {
            this.msg = msg;
        }
    
        public String getMessage() {
            return message;
        }
    
        public void setMessage(String message) {
            this.message = message;
        }
    
        public T getData() {
            return data;
        }
    
        public void setData(T data) {
            this.data = data;
        }
    
        public Result ok(T t){
            this.setCode(1000);
            this.setMsg("成功");
            this.setMessage("成功");
            this.setData(t);
            return this;
        }
    
        public Result fail(String msg){
            this.setCode(1001);
            this.setMsg(msg);
            this.setMessage(msg);
            return this;
        }
    
    
        public Result() {
        }
    
        public Result(Integer code, String msg) {
            this.code = code;
            this.msg = msg;
            this.setMessage(msg);
        }
    
        public Result(Integer code, String msg, T data) {
            this.code = code;
            this.msg = msg;
            this.data = data;
            this.setMessage(msg);
        }
    
    }
    
    • 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

    entity

    User.java

    package com.demo.entity;
    
    import com.baomidou.mybatisplus.annotation.*;
    import com.fasterxml.jackson.annotation.JsonFormat;
    
    import java.io.Serializable;
    import java.util.Date;
    
    /**
     * 

    * 用户表 *

    * * @author Leo825 * @since 2022-07-05 */
    @TableName("t_user") public class User implements Serializable { private static final long serialVersionUID = 1L; /** * 用户主键 */ @TableId(value = "id", type = IdType.AUTO) private Integer id; /** * 用户名称 */ private String username; /** * 密码 */ private String pwd; /** * 创建时间,MyMetaObjectHandler 配合使用,入库的时候自动填充 */ @TableField(value = "create_time", fill = FieldFill.INSERT) @JsonFormat(timezone = "GMT+8", pattern = "yyyy-MM-dd HH:mm:ss") private Date createTime; /** * 修改时间,MyMetaObjectHandler 配合使用,入库的时候自动填充 */ @TableField(value = "update_time", fill = FieldFill.INSERT_UPDATE) @JsonFormat(timezone = "GMT+8", pattern = "yyyy-MM-dd HH:mm:ss") private Date updateTime; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getPwd() { return pwd; } public void setPwd(String pwd) { this.pwd = pwd; } public Date getCreateTime() { return createTime; } public void setCreateTime(Date createTime) { this.createTime = createTime; } public Date getUpdateTime() { return updateTime; } public void setUpdateTime(Date updateTime) { this.updateTime = updateTime; } @Override public String toString() { return "User{" + "id=" + id + ", username=" + username + ", pwd=" + pwd + ", createTime=" + createTime + ", updateTime=" + updateTime + "}"; } }
    • 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
    • 75
    • 76
    • 77
    • 78
    • 79
    • 80
    • 81
    • 82
    • 83
    • 84
    • 85
    • 86
    • 87
    • 88
    • 89
    • 90
    • 91
    • 92
    • 93
    • 94
    • 95
    • 96
    • 97
    • 98
    • 99

    mapper

    package com.demo.service.impl;
    
    import com.demo.entity.User;
    import com.demo.mapper.UserMapper;
    import com.demo.service.IUserService;
    import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
    import org.springframework.stereotype.Service;
    
    /**
     * 

    * 用户表 服务实现类 *

    * * @author Leo825 * @since 2022-07-05 */
    @Service public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService { }
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20

    service

    package com.demo.service;
    
    import com.demo.entity.User;
    import com.baomidou.mybatisplus.extension.service.IService;
    
    /**
     * 

    * 用户表 服务类 *

    * * @author Leo825 * @since 2022-07-05 */
    public interface IUserService extends IService<User> { }
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16

    impl 实现类:

    package com.demo.service.impl;
    
    import com.demo.entity.User;
    import com.demo.mapper.UserMapper;
    import com.demo.service.IUserService;
    import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
    import org.springframework.stereotype.Service;
    
    /**
     * 

    * 用户表 服务实现类 *

    * * @author Leo825 * @since 2022-07-05 */
    @Service public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService { }
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20

    config

    MybatisPlusConfig.java

    package com.demo.config;
    
    import com.baomidou.mybatisplus.annotation.DbType;
    import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
    import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
    import org.springframework.context.annotation.Bean;
    import org.springframework.context.annotation.Configuration;
    
    /**
     * mybatisplus 配置
     */
    @Configuration
    public class MybatisPlusConfig {
        /**
         * 老版本,目前已失效
         * @return
         */
        /**@Bean
        public PaginationInterceptor paginationInterceptor() {
        PaginationInterceptor paginationInterceptor = new PaginationInterceptor();
        return paginationInterceptor;
        }*/
    
    
        /**
         * 新的分页插件,一缓和二缓遵循mybatis的规则,
         */
        @Bean
        public MybatisPlusInterceptor mybatisPlusInterceptor() {
            MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
            interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.H2));
            return interceptor;
        }
    }
    
    • 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

    MyMetaObjectHandler.java

    package com.demo.config;
    
    import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
    import lombok.extern.slf4j.Slf4j;
    import org.apache.ibatis.reflection.MetaObject;
    import org.springframework.stereotype.Component;
    
    import java.util.Date;
    
    /**
     * 填充公共字段
     *
     */
    @Slf4j
    @Component
    public class MyMetaObjectHandler implements MetaObjectHandler {
        @Override
        public void insertFill(MetaObject metaObject) {
            log.info("start insert fill...");
            this.setFieldValByName("createTime", new Date(), metaObject);
            this.setFieldValByName("updateTime", new Date(), metaObject);
        }
    
        @Override
        public void updateFill(MetaObject metaObject) {
            log.info("start update fill...");
            this.setFieldValByName("updateTime",  new Date(), metaObject);
        }
    }
    
    • 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

    controller

    package com.demo.controller;
    
    
    import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
    import com.baomidou.mybatisplus.core.metadata.IPage;
    import com.baomidou.mybatisplus.core.toolkit.StringUtils;
    import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
    import com.demo.base.Result;
    import com.demo.entity.User;
    import com.demo.service.IUserService;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.web.bind.annotation.GetMapping;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.RestController;
    
    import java.util.List;
    
    /**
     * controller 测试
     *
     */
    @RestController
    @RequestMapping("/user")
    public class UserController {
    
        /**
         * 构造方法注入
         */
        @Autowired
        IUserService userService;
    
    
        /**
         * 保存数据
         *
         * @return
         */
        @GetMapping("/save")
        public Result save() {
            User user = new User();
            user.setId(10);
            user.setUsername("miaolinlin");
            user.setPwd("121212");
            userService.save(user);
            return new Result().ok(user);
        }
    
        /**
         * 修改数据
         *
         * @param id
         * @return
         */
        @GetMapping("/update")
        public Result update(Integer id) {
            User user = new User();
            user.setId(id);
            user.setPwd("1111111111");
            userService.updateById(user);
            return new Result().ok("{}");
        }
    
        @GetMapping("/list")
        public Result list() {
            // 返回所有
            List<User> list = userService.list();
            return new Result().ok(list);
        }
    
        @GetMapping("/listByContion")
        public Result listByContion() {
            /**
             * 条件查询, 通过QueryWrapper来实现查询的条件:
             * eq: 代表相等
             * like: 模糊匹配
             * orderBy: 排序
             * in, notin
             * 大于,小于,between等
             */
            List<User> list = userService.list(new LambdaQueryWrapper<User>()
                    // 查询年龄=11的
                    .eq(User::getUsername, "miao")
                    // 模糊匹配
                    .like(User::getPwd, "%111%")
                    // 排序,按照创建时间
                    .orderByDesc(User::getCreateTime)
            );
            return new Result().ok(list);
        }
    
        /**
         * 根据id获取数据
         *
         * @param id
         * @return
         */
        @GetMapping("/getById")
        public Result getById(Integer id) {
            User user = userService.getById(id);
            return new Result().ok(user);
        }
    
        /**
         * 删除数据
         *
         * @param id
         * @return
         */
        @GetMapping("/delete")
        public Result delete(Integer id) {
            userService.removeById(id);
            return new Result().ok("success");
        }
    
        /**
         * 分页查询
         *
         * @param pageNum
         * @param pageSize
         * @param name
         * @return
         */
        @GetMapping("/page")
        public Result page(int pageNum, int pageSize, String name) {
            IPage<User> page = new Page<>(pageNum, pageSize);
    
            IPage<User> page1 = userService.page(page, new LambdaQueryWrapper<User>()
                    // 主要演示这里可以加条件。在name不为空的时候执行
                    .like(StringUtils.isNotEmpty(name), User::getUsername, "%" + name + "%"));
    
            return new Result().ok(page1);
        }
    }
    
    • 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
    • 75
    • 76
    • 77
    • 78
    • 79
    • 80
    • 81
    • 82
    • 83
    • 84
    • 85
    • 86
    • 87
    • 88
    • 89
    • 90
    • 91
    • 92
    • 93
    • 94
    • 95
    • 96
    • 97
    • 98
    • 99
    • 100
    • 101
    • 102
    • 103
    • 104
    • 105
    • 106
    • 107
    • 108
    • 109
    • 110
    • 111
    • 112
    • 113
    • 114
    • 115
    • 116
    • 117
    • 118
    • 119
    • 120
    • 121
    • 122
    • 123
    • 124
    • 125
    • 126
    • 127
    • 128
    • 129
    • 130
    • 131
    • 132
    • 133

    H2 的 web 访问

    例如我的访问方式:http://localhost:8080/springboot-h2/h2-console
    h2访问
    填写上自己配置文件里的连接方式,就可以访问库了。

    总结

    springboot 整合 h2 和 sqlite、mysql 差不多,代码库地址如下:

    https://gitee.com/leo825/springboot-learning-parents.git

  • 相关阅读:
    Allegro PCB编辑界面功能全面介绍图文教程
    机器学习(十八):随机搜索和XGBoost
    2、k8s 集群安装
    阿里巴巴《MySQL成长手册》精简版
    客户成功体系如何构建?请看这7步
    信息学奥赛一本通:1839:【05NOIP提高组】谁拿了最多奖学金
    肖sir__mysql之navicat安装__003
    [附源码]Python计算机毕业设计SSM景区在线购票系统(程序+LW)
    企业级开源版本管理系统GIT分析
    二十一、Java 继承
  • 原文地址:https://blog.csdn.net/u011047968/article/details/125999917