gpt4 book ai didi

java - Spring Boot 不会自动创建表

转载 作者:行者123 更新时间:2023-12-04 12:07:58 25 4
gpt4 key购买 nike

当 Spring Boot 尝试在表中插入数据时,我遇到了错误。我正在使用 H2 和 Spring Boot 2.5.0。似乎 Spring 没有创建表。
这是我的实体

@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 h2spring-boot-starter-data-jpa .
当我以 Debug模式启动服务器时,出现此错误:
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', 'mitchell.hudson11@example.com'); 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', 'mitchell.hudson11@example.com') [42102-200]
这是我的data.sql
INSERT INTO users (id, name, surname, email) VALUES (1, 'Mitchell', 'Hudson', 'mitchell.hudson11@example.com');
INSERT INTO users (id, name, surname, email) VALUES (2, 'Melanie', 'Bell', 'melanie.bell51@example.com');
INSERT INTO users (id, name, surname, email) VALUES (3, 'Diane', 'Ruiz', 'diane.ruiz24@example.com');
我在属性文件中尝试了一些配置,但无法修复错误。
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
我可以看到插入数据的查询,但它没有生成查询来创建表,所以我认为问题出在那里。
提前致谢。

最佳答案

Spring Boot 2.5 中重新设计了 SQL 脚本数据源初始化功能。

By default, data.sql scripts are now run before Hibernate isinitialized. This aligns the behavior of basic script-basedinitialization with that of Flyway and Liquibase. If you want to usedata.sql to populate a schema created by Hibernate, setspring.jpa.defer-datasource-initialization to true. While mixingdatabase initialization technologies is not recommended, this willalso allow you to use a schema.sql script to build upon aHibernate-created schema before it’s populated via data.sql.


引用
Spring Boot 2.5 Release Notes

关于java - Spring Boot 不会自动创建表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67678311/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com