H2数据库在SpringBoot环境下的配置与使用攻略

Outshine 2018-11-18 | 阅读 7795

H2是一个开源的、纯Java实现的嵌入式数据库引擎,不受平台的限制,可以兼容一些主流的数据库,因此采用H2作为开发期的数据库非常方便。

H2的优势:
1、h2采用纯Java编写,因此不受平台的限制。
2、h2只有一个jar文件,十分适合作为嵌入式数据库试用。
3、支持标准的sql和jdbc。
4、支持内嵌模式,服务器模式和集群。
5、h2提供了一个十分方便的web控制台用于操作和管理数据库内容。

在Spring Boot环境中配置H2

    datasource:
        driver-class-name: org.h2.Driver # 驱动
        #url: jdbc:h2:file:/home/websoso #h2
        url: jdbc:h2:file:./数据库名 #h2 本地数据库文件
        username: username
        password: password

这里还引入了jpa 用来对H2进行操作

    jpa:
        database: h2
        show-sql: false
        hibernate:
            ddl-auto: update
        properties:
            hibernate.format_sql: true
            hibernate.naming.physical-strategy: org.hibernate.boot.model.naming.PhysicalNamingStrategyStandardImpl
            hibernate.cache.use_second_level_cache: false
            hibernate.search.default.directory_provider: filesystem
    h2:     #h2数据库远程管理
        console:
          enabled: true #开启web显示
          path: /db # 路径
          settings:
            web-allow-others: true
            trace: true #是否可以远程web

ALTER USER

修改用户名:

alter user websoso rename to wangsoso

修改用户密码:

alter user username set password 'password'

修改字段默认值

alter table 表名 drop constraint 约束名字   ------说明:删除表的字段的原有约束

alter table 表名 add constraint 约束名字 DEFAULT 默认值 for 字段名称 -------说明:添加一个表的字段的约束并指定默认值

修改字段类型:

alter table 表名 alter column UnitPrice decimal(18, 4) not null

增加字段:

alter table 表名 ADD 字段 类型 NOT NULL Default 0

修改字段名:

alter table 表名  rename column A to B