启动 Spring 启动应用程序时无法将数据插入 H2 数据库

Can't insert data into H2 database when starting Spring Boot app

我第一次使用 h2 数据库,当 Spring 启动我的应用程序时,我一直在尝试将数据插入数据库。我将它设置为一个文件数据库,以便能够从控制台和 IntelliJ 访问它。我可以看到表格,当我在 data.sql 文件下按 运行 时,数据会插入,但不会在应用程序启动时自动插入。

表格是自动创建的,没有 sql 文件,但通过 data.sql 文件插入数据将不起作用。即使我们手动填充数据库,稍后我的 repository.count() 调用仍将是 return 0,我认为这可能与第一个问题有关,因为它可能找不到数据库。 我已经尝试修复此问题两天了,但我真的无法弄清楚我错过了什么。

spring.jpa.hibernate.ddl-auto=update
# Enabling H2 Console
spring.h2.console.enabled=true
#spring.datasource.url=jdbc:h2:mem:testdb
spring.datasource.url=jdbc:h2:file:./src/main/resources/data/resume-portal;MV_STORE=false;AUTO_SERVER=TRUE
spring.data.jpa.repositories.bootstrap-mode=default
spring.jpa.defer-datasource-initialization=true
spring.datasource.username=sa
spring.datasource.password=
spring.jpa.database-platform=org.hibernate.dialect.H2Dialect
server.port=8888
spring.sql.init.data-locations=classpath:data.sql
@Entity
@Table(name = "User")
public class User {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    public int id;
    public String userName;
    public String password;
    public boolean active;
    public String roles;

... getters and setters as well

@EnableWebSecurity(debug = true)
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {

    @Autowired
    UserDetailsService userDetailsService;

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userDetailsService);
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
                .antMatchers("/edit").authenticated()
                .antMatchers("/console/**").permitAll()
                .antMatchers("/login").permitAll()
                .antMatchers("/*").permitAll()
                .and().formLogin()
                .failureHandler(new AuthenticationFailureHandler() {

                    @Override
                    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) {
                        System.out.println("A user has failed to login. Error: " + exception.getMessage());
                    }
                })
                .permitAll();

        http.csrf().disable();
        http.headers().frameOptions().disable();
    }

    @Bean
    public PasswordEncoder getPasswordEncoder() {
        return NoOpPasswordEncoder.getInstance();
    }

}

https://github.com/francislainy/resume-portal

谢谢。

更新

使用内存数据库而不是文件类型是可行的。不知道为什么。

spring.datasource.url=jdbc:h2:mem:testdb

默认情况下,Spring Boot 的 auto-configuration 只执行嵌入式数据库的 sql 初始化脚本。当您使用 file-based 而不是 in-memory 数据库时,Spring Boot 不再认为数据库是嵌入的。

您可以通过设置 属性

显式启用初始化
spring.sql.init.mode=always

请同时查看官方文档:https://docs.spring.io/spring-boot/docs/2.6.4/reference/html/howto.html#howto.data-initialization.using-basic-sql-scripts