Spring Boot 中使用 H2 数据库

Spring Security 使用H2数据库 : https://yuanyu.blog.csdn.net/article/details/106353965

http://www.h2database.com/html/main.html 


1 加依赖


    
        
        
            org.springframework.boot
            spring-boot-dependencies
            2.3.0.RELEASE
            pom
            import
        
    


    org.springframework.boot
    spring-boot-starter-data-jpa


    com.h2database
    h2
    runtime



    org.springframework.boot
    spring-boot-starter-web


    org.springframework.boot
    spring-boot-starter-test
    test



    org.projectlombok
    lombok
    provided

resources目录下创建data-h2.sql 

INSERT INTO `user` (`username`, `password`, `name`, `age`, `email`)
VALUES ('zhangsan', '123456', '张三', '18', '[email protected]'),
       ('lisi', '123456', '李四', '20', '[email protected]'),
       ('wangwu', '123456', '王五', '28', '[email protected]'),
       ('zhaoliu', '123456', '赵六', '21', '[email protected]'),
       ('sunqi', '123456', '孙七', '24', '[email protected]');

2 写配置

############################################################
#
# h2 配置 http://localhost:6969/h2-console
#
############################################################
spring.datasource.platform=h2
spring.h2.console.enabled=true
spring.h2.console.path=/h2-console
spring.datasource.url=jdbc:h2:mem:user_db;DB_CLOSE_ON_EXIT=FALSE
spring.datasource.driver-class-name=org.h2.Driver
spring.datasource.username=root
spring.datasource.password=123456
############################################################
#
# spring data 配置
#
############################################################
spring.jpa.show-sql=true
spring.jpa.generate-ddl=true
spring.jpa.properties.hibernate.show_sql=true
spring.jpa.properties.hibernate.format_sql=true
spring.h2.console.settings.web-allow-others=false
spring.h2.console.settings.trace=false

3 Java 代码

@Data
@Entity
public class User {
    /**
     * 主键ID
     */
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    /**
     * 用户名
     */
    @Column(unique = true, length = 20)
    private String username;
    /**
     * 密码
     */
    @Column(length = 64)
    private String password;
    /**
     * 姓名
     */
    @Column(length = 20)
    private String name;
    /**
     * 年龄
     */
    private Integer age;
    /**
     * 邮箱
     */
    @Column(length = 50)
    private String email;
public interface UserRepository extends JpaRepository {}

4 效果演示

Spring Boot 中使用 H2 数据库_第1张图片


5 源码

package org.springframework.boot.autoconfigure.h2;
@Configuration(proxyBeanMethods = false)
@ConditionalOnWebApplication(type = Type.SERVLET)
@ConditionalOnClass(WebServlet.class)
@ConditionalOnProperty(prefix = "spring.h2.console", name = "enabled", havingValue = "true", matchIfMissing = false)
@AutoConfigureAfter(DataSourceAutoConfiguration.class)
@EnableConfigurationProperties(H2ConsoleProperties.class)
public class H2ConsoleAutoConfiguration {
    private static final Log logger = LogFactory.getLog(H2ConsoleAutoConfiguration.class);
    @Bean
    public ServletRegistrationBean h2Console(H2ConsoleProperties properties, ObjectProvider dataSource) {
        String path = properties.getPath();
        String urlMapping = path + (path.endsWith("/") ? "*" : "/*");
        ServletRegistrationBean registration = new ServletRegistrationBean<>(new WebServlet(), urlMapping);
        H2ConsoleProperties.Settings settings = properties.getSettings();
        if (settings.isTrace()) {
            registration.addInitParameter("trace", "");
        }
        if (settings.isWebAllowOthers()) {
            registration.addInitParameter("webAllowOthers", "");
        }
        dataSource.ifAvailable((available) -> {
            try (Connection connection = available.getConnection()) {
                logger.info("H2 console available at '" + path + "'. Database available at '" + connection.getMetaData().getURL() + "'");
            } catch (SQLException ex) {
                // Continue
            }
        });
        return registration;
    }
}
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.util.Assert;
@ConfigurationProperties(prefix = "spring.h2.console")
public class H2ConsoleProperties {
    /**
     * Path at which the console is available.
     */
    private String path = "/h2-console";
    /**
     * Whether to enable the console.
     */
    private boolean enabled = false;
    private final Settings settings = new Settings();
    public String getPath() {return this.path;}
    public void setPath(String path) {
        Assert.notNull(path, "Path must not be null");
        Assert.isTrue(path.length() > 1, "Path must have length greater than 1");
        Assert.isTrue(path.startsWith("/"), "Path must start with '/'");
        this.path = path;
    }
    public boolean getEnabled() {return this.enabled;}
    public void setEnabled(boolean enabled) {this.enabled = enabled;}
    public Settings getSettings() {return this.settings;}
    public static class Settings {
        /**
         * Whether to enable trace output.
         */
        private boolean trace = false;
        /**
         * Whether to enable remote access.
         */
        private boolean webAllowOthers = false;
        public boolean isTrace() {return this.trace; }
        public void setTrace(boolean trace) {this.trace = trace;}
        public boolean isWebAllowOthers() {return this.webAllowOthers;}
        public void setWebAllowOthers(boolean webAllowOthers) {this.webAllowOthers = webAllowOthers;}
    }
}

 

你可能感兴趣的:(SpringBoot)