问题描述
当 Spring Boot 尝试在表中插入数据时,我遇到了错误.我正在使用 H2 和 Spring Boot 2.5.0.似乎 Spring 没有创建表.
I'm facing an error when Spring Boot try to insert data in a table. I'm using H2 and Spring Boot 2.5.0. It's seems that Spring is not creating the table.
这是我的实体
@Entity(name = "Users")
@Table(name = "users")
public class UserEntity implements Serializable {
// Serial
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
private String name;
private String surname;
private String email;
// Getters and setters
}
还有我的仓库
public interface UserRepository extends JpaRepository<UserEntity, Integer> {
}
我已经添加到我的 pom.xml h2
和 spring-boot-starter-data-jpa
.
I have added to my pom.xml h2
and spring-boot-starter-data-jpa
.
当我以调试模式启动服务器时,出现此错误:
When I start the server in debug mode I got this error:
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'dataSourceScriptDatabaseInitializer' defined in class path resource [org/springframework/boot/autoconfigure/sql/init/DataSourceInitializationConfiguration.class]: Invocation of init method failed; nested exception is org.springframework.jdbc.datasource.init.ScriptStatementFailedException: Failed to execute SQL script statement #1 of URL [file:/PATH/target/classes/data.sql]: INSERT INTO users (id, name, surname, email) VALUES (1, 'Mitchell', 'Hudson', '[email protected]'); nested exception is org.h2.jdbc.JdbcSQLSyntaxErrorException: Tabla "USERS" no encontrada
Table "USERS" not found; SQL statement:
INSERT INTO users (id, name, surname, email) VALUES (1, 'Mitchell', 'Hudson', '[email protected]') [42102-200]
这是我的数据.sql
INSERT INTO users (id, name, surname, email) VALUES (1, 'Mitchell', 'Hudson', '[email protected]');
INSERT INTO users (id, name, surname, email) VALUES (2, 'Melanie', 'Bell', '[email protected]');
INSERT INTO users (id, name, surname, email) VALUES (3, 'Diane', 'Ruiz', '[email protected]');
我在属性文件中尝试了一些配置,但无法修复错误.
I try some configuration in properties file but I wasn't able to fix the error.
spring.jpa.generate-ddl=true
spring.jpa.hibernate.ddl-auto=create-drop
spring.datasource.url=jdbc:h2:mem:testdb
spring.datasource.username=sa
spring.datasource.password=sa
spring.datasource.driver-class-name=org.h2.Driver
我可以看到插入数据的查询,但它没有生成创建表的查询,所以我认为问题出在那里.
I can see the query to insert data but it's not generating query to create the table so I think that the problem is there.
提前致谢.
推荐答案
SQL 脚本数据源初始化功能已在 Spring Boot 2.5 中重新设计.
The SQL Script DataSource Initialization feature has been redesigned in Spring Boot 2.5.
默认情况下,data.sql
脚本现在在 Hibernate 之前运行初始化.这与基于脚本的基本行为保持一致Flyway 和 Liquibase 的初始化.如果你想使用data.sql
填充由 Hibernate 创建的模式,设置spring.jpa.defer-datasource-initialization
到 true
.搅拌时不推荐使用数据库初始化技术,这会还允许您使用 schema.sql
脚本来构建在通过 data.sql
填充之前由 Hibernate 创建的模式.
参考
这篇关于Spring Boot 不会自动创建表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!