新增内存数据库(In-Memory)h2-database支持

2018-09-09  本文已影响0人  Vinko_wei

内存数据库h2-Database 简介:

详情点击 h2-database 官网

h2-Database 由纯 Java 编写的开源内存数据库,可以直接嵌入到应用程序中,不受平台约束,便于测试

h2支持运行三种模式


在sample上面配置h2, 跳了很多该跳和不该条的坑,解决了一些疑问,也有些我不会解决,下面我都列出来。


在sample上面配置h2-database 并测试CRUD操作主要步骤:
  1. pom.xml中添加h2spring-data-jpa的依赖
  2. applicatoin.yml中配置datasourceh2-datasource 相关属性
  3. 编写相关测试实体类
  4. 编写测试类
具体实现:
        <dependency>
            <groupId>com.h2database</groupId>
            <artifactId>h2</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>

解释: <scope>test<scope>: 在测试时引入依赖,其他选项: runtime 运行时.

spring:
    h2:
    console:
      enabled: true     #开启web端 h2-console ,此项目访问路径为: localhost/h2-console
     #path:     此处可以修改默认的/h2-console为其他路径

官方: URL规则

@Entity
public class User {
    @Id
    @GeneratedValue()
    private long id;
    private String name;
    ---省略getter setter
}
                .authorizeRequests()
                .antMatchers("/h2-console/**").permitAll()   //允许通过
                .anyRequest().permitAll()
                .and()
                .csrf().ignoringAntMatchers("/h2-console/**") //跨站请求伪造拦截忽略
                .and()
                .headers().frameOptions().disable() // 关闭x-frame检测

如果没有以上配置,Spring Security 安全认证会拦截/h2-console

启动~ 成功~
image.png
image.png

发现数据库中已经有了我们的USER表了。Magic~

上一篇 下一篇

猜你喜欢

热点阅读