Spring开机spring.datasource.schemaVSspring.jpa.properties.hibernate.default_schema

Spring Boot spring.datasource.schema VS spring.jpa.properties.hibernate.default_schema

最近,我开始使用 Spring Boot 进行 Web 应用程序开发。

这是我的 .properties 文件内容:

#data source configuration
spring.datasource.url=jdbc:postgresql://localhost:5432/sampledb
spring.datasource.schema=sample
spring.datasource.username=postgres
spring.datasource.password=postgres
spring.datasource.driver-class-name=org.postgresql.Driver
#spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.minimumIdle=3
spring.datasource.maximumPoolSize=5



#jpa properties configuration
#spring.jpa.show-sql=false
spring.jpa.databasePlatform=org.hibernate.dialect.PostgreSQL82Dialect
spring.jpa.properties.hibernate.show_sql=true
spring.jpa.hibernate.ddl-auto=validate
#spring.jpa.properties.hibernate.default_schema=sample

我实体的这一部分class:

@Entity
@Table(name = "sample_info")
public class SampleInfo implements Serializable{

    private Long id;
    private String code;
    private Long serialNumber;

    @Id
    @GeneratedValue(
            strategy = GenerationType.SEQUENCE,
            generator = "sample_info_seq_gen"
    )
    @SequenceGenerator(
            name = "sample_info_seq_gen",
            sequenceName = "sample_info_seq",
            allocationSize = 1
    )
    @Column(name = "id")
    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

基于上面的 .properties,问题是每次我尝试使用 Spring Data JPA 存储库保存新的 SampleInfo 时,我总是得到错误序列 "sample_info_seq" 未找到。

如果我注释 spring.datasource.schema=sample 并取消注释 spring.jpa.properties.hibernate.default_schema=sample,一切正常。

我不知道这两者之间的区别,谁能帮忙?

spring.datasource.schema 被 Spring boot 用来将带有 sql 的文件加载到您的数据库中。如果你使用这个 Postgres 会认为你想使用默认的 'public' 模式。

spring.jpa.properties.hibernate.default_schema 告诉 Hibernate 你想使用 Postgres 中的哪个模式。通过根据您的示例进行设置,Postgres 将使用 'sample' 架构。