【问题标题】:data.sql with spring boot JPA Postresql is not loading带有spring boot JPA Postgresql的data.sql未加载
【发布时间】:2020-10-18 01:36:41
【问题描述】:

我已经编写了一个 Spring Boot 应用程序。我想用 data.sql 文件设置初始数据库数据。

src/main/resources/application.properties

spring.jpa.hibernate.ddl-auto=create
spring.datasource.url=${JDBC_DATABASE_URL}
spring.datasource.driver-class-name=org.postgresql.Driver
spring.datasource.initialization-mode=always
spring.jpa.show-sql=true

src/main/java/package_name/model/my_entity

@Entity
@Table(name = "user_entry")
public class User {
    @Id
    @Column(nullable = false, length = 50)
    private String userId;
    @Column(nullable = false, length = 50)
    private String firstName;
    @Column(nullable = false, length = 50)
    private String lastName;
    @Column(nullable = false, length = 50)
    private String password;
    @OneToMany(mappedBy = "owner", cascade = CascadeType.ALL, orphanRemoval = true)
    private Set<SongList> songLists;

    public User() {
    }
    ...
}

src/main/resources/data.sql

insert into user_entry (user_id, first_name, last_name, password) values
('MaMu', 'Maxime', 'Muster', 'pass1234');

但是在部署期间数据似乎没有加载到数据库中。

编辑:

在我的 src/main/resources/application.properties 中添加 spring.datasource.data= classpath:/data.sql 解决了这个问题。

【问题讨论】:

    标签: java postgresql spring-boot hibernate jpa


    【解决方案1】:

    我们有这些属性来创建记录并将其插入表中。因为你只需要插入记录就可以避免spring.datasource.schema

    spring.datasource.schema= # Schema (DDL) script resource references.
    spring.datasource.data= # Data (DML) script resource references.
    

    设置 SQL 文件

    spring.datasource.data= classpath:/data.sql
    

    注意事项:

    • 对于同一个文件中的模式生成和插入,不要使用spring.datasource.data,我们必须使用spring.datasource.schema
    • 将所有文件保存在 src/main/resources
    • 设置spring.datasource.initialization-mode=always
    • 还要确保您没有使用spring.jpa.generate-ddl=true,因为它会在幕后设置hibernate.hbm2ddl.auto=update,并使spring.jpa.hibernate.ddl-auto=create 无效

    【讨论】:

    【解决方案2】:

    如果您的实体未被考虑在您的 Springboot 主类上添加下面的注释,就在您的 @SpringBootApplication 注释下方,

    @EntityScan(basePackages = {"package_name.model.my_entity"}
    

    此外,从实体中删除 @Id 标记后它对我有用(不确定这可能是原因)。

    【讨论】:

    • 对不起,这个版本让我的整个应用程序在启动时崩溃
    猜你喜欢
    • 2021-08-17
    • 1970-01-01
    • 2020-09-29
    • 2021-02-09
    • 2021-11-09
    • 2018-05-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多