H2数据库

19 年 9 月 11 日 星期三
438 字
3 分钟

H2数据库、SpringBoot配置、IDEA 数据库管理

H2数据库

体积小,轻便,可以嵌入到应用中的数据库。

简要提一下。

  • 官网的QuickStart
  • Maven依赖
xml
<!-- h2数据库-->
        <dependency>
            <groupId>com.h2database</groupId>
            <artifactId>h2</artifactId>
            <version>1.4.199</version>
            <scope>runtime</scope>
        </dependency>
  • SpringBoot配置

application.properties

properties
#h2数据库配置
spring.datasource.url=jdbc:h2:~/H2database
spring.datasource.username=***
spring.datasource.password=***
spring.datasource.driver-class-name=org.h2.Driver

application.yml

yml
# h2 DataSource Config
spring:
  datasource:
    driver-class-name: org.h2.Driver
    schema: classpath:db/schema-h2.sql
    data: classpath:db/data-h2.sql
    url: jdbc:h2:~/H2database
    username: ***
    password: ***

需要引入spring-jdbc,自动配置嵌入式的数据库

spring-jdbc

xml
<!--    spring-jdbc 自动配置嵌入式数据库   -->
<dependency>
	<groupId>org.springframework.boot</groupId>
	<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
  • IDEA连接H2数据库

这里提一下,应该都知道的,idea自带有数据库管理的。

这样填,选Embedded(嵌入),用户密码可以不设,path是路径,~是当前用户的文件夹,H2database是数据库名

比如图中的h2数据库实际位于(~/H2database):

测试用的数据表

sql
create table USER
(
	ID BIGINT auto_increment,
	NICKNAME VARCHAR(100) not null,
	PASSWORD VARCHAR(100),
	EMAIL VARCHAR(200) not null
		constraint USER_EMAIL_UINDEX
			unique,
	AVATARIMAGE VARCHAR(500),
	GITHUB_ID VARCHAR(500)
		constraint USER_GITHUB_ID_UINDEX
			unique,
	GMT_CREATE BIGINT not null,
	GMT_MODIFIED BIGINT not null,
	constraint USER_PK
		primary key (ID)
);

comment on table USER is '论坛的用户表';

comment on column USER.GMT_CREATE is '创建时间戳';

comment on column USER.GMT_MODIFIED is '变更时间戳';

create unique index USER_ID_UINDEX
	on USER (ID);

其他数据库,像MySQL也是类似配置,顺便附Mybatis的Spring Boot配置:

Maven依赖

xml
<!--     mybatis   -->
<dependency>
  <groupId>org.mybatis.spring.boot</groupId>
  <artifactId>mybatis-spring-boot-starter</artifactId>
  <version>2.1.0</version>
</dependency>

Gradle的依赖

Gradle和Maven作用类似,还是很好用的,只是网好像有点慢,可能是我网络的问题。

text
dependencies {
  compile("org.mybatis.spring.boot:mybatis-spring-boot-starter:2.1.0")
}

mybatis下划线转驼峰

如:user_id -> userId

实际上就是把数据库表中的字段下划线去除,然后再设置大小写不敏感。这是springboot里的配置方式:

application.properties

properties
mybatis.configuration.map-underscore-to-camel-case=true

顺便回顾下SSM的:

mybatis的配置文件,在<configuration标签配置:

xml
<settings>
     <setting name="mapUnderscoreToCamelCase" value="true"/>
</settings>

最后,推荐MyBatis-Plus,很好用。

然后是springboot的文档

文章标题:H2数据库

文章作者:shirtiny

文章链接:https://kizamu.anror.com/posts/h2-database[复制]

最后修改时间:


商业转载请联系站长获得授权,非商业转载请注明本文出处及文章链接,您可以自由地在任何媒体以任何形式复制和分发作品,也可以修改和创作,但是分发衍生作品时必须采用相同的许可协议。
本文采用CC BY-NC-SA 4.0进行许可。