Spring Boot 中使用 H2 數據庫

Spring Security 使用H2數據庫 : https://yuanyu.blog.csdn.net/article/details/106353965

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


1 加依賴

<dependencyManagement>
    <dependencies>
        <!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-dependencies -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-dependencies</artifactId>
            <version>2.3.0.RELEASE</version>
            <type>pom</type>
            <scope>import</scope>
        </dependency>
    </dependencies>
</dependencyManagement>
<!-- db -->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
    <groupId>com.h2database</groupId>
    <artifactId>h2</artifactId>
    <scope>runtime</scope>
</dependency>
<!-- boot -->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-test</artifactId>
    <scope>test</scope>
</dependency>
<!--other-->
<dependency>
    <groupId>org.projectlombok</groupId>
    <artifactId>lombok</artifactId>
    <scope>provided</scope>
</dependency>

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<User, Long> {}

4 效果演示


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<WebServlet> h2Console(H2ConsoleProperties properties, ObjectProvider<DataSource> dataSource) {
        String path = properties.getPath();
        String urlMapping = path + (path.endsWith("/") ? "*" : "/*");
        ServletRegistrationBean<WebServlet> 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;}
    }
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章