如何为 Spring Data JPA 查询设置默认架构名称?

hel*_*one 8 java spring hibernate spring-data-jpa spring-boot

我想为 postgresql 设置默认架构。当我尝试设置 property("hibernate.default_schema") 并使用 schema 属性更新表注释时,hibernate 仍然会生成没有任何模式名称的查询,如下所示;

select log0_.id as id1_0_ from log log0_
Run Code Online (Sandbox Code Playgroud)

当我将表名更改为“dbo.log”时,我可以获得结果集而不会出现任何错误。

 @Table(name = "dbo.log")
Run Code Online (Sandbox Code Playgroud)

有没有办法为 postgresql 查询设置默认模式?

@Configuration
@EnableJpaRepositories(
    basePackages = "com.test.repository.postgresql",
    entityManagerFactoryRef = "postgresqlEntityManagerFactory",
    transactionManagerRef = "postgresqlTransactionManager"
)
public class PostgreSQLConfig {

    ....

    @Bean(name = "postgresqlEntityManagerFactory")
    public EntityManagerFactory entityManagerFactory(@Qualifier("postgresqlDatasource") DataSource postgresqlDatasource) {

        Properties jpaProperties = new Properties();
        jpaProperties.setProperty("hibernate.dialect", hibernateDialect);
        jpaProperties.setProperty("hibernate.show_sql", hibernateShowSql);
        jpaProperties.setProperty("hibernate.ddl-auto", hibernateDDLAuto);
        jpaProperties.setProperty("hibernate.naming.physical-strategy", hibernatePhysicalStrategy);
        jpaProperties.setProperty("hibernate.default_schema", "dbo");

        HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
        vendorAdapter.setDatabase(Database.POSTGRESQL);
        LocalContainerEntityManagerFactoryBean factory = new LocalContainerEntityManagerFactoryBean();
        factory.setJpaVendorAdapter(vendorAdapter);
        factory.setJpaProperties(jpaProperties);
        factory.setPackagesToScan("com.test.entity.postgresql");
        factory.setDataSource(postgresqlDatasource);
        factory.afterPropertiesSet();
        return factory.getObject();
    }

}
Run Code Online (Sandbox Code Playgroud)

这是我的实体类;

@Entity
@Table(name = "log", schema = "dbo")
public class Log{
    ....
}
Run Code Online (Sandbox Code Playgroud)

Orç*_*lak 5

如果您正在使用 application.properties

spring.datasource.url=jdbc:postgresql://myserver:5432/mydb

spring.jpa.properties.hibernate.default_schema=myschema

spring.datasource.username=myuser

spring.datasource.password=我的密码

spring.datasource.driver-class-name=org.postgresql.Driver


Rob*_*roj 1

这应该在DataSource. URL 架构类似于:jdbc:postgresql://host:port/database,其中数据库是架构。

如果这还不够,请在 URL 中设置currentSchema.

指定要在搜索路径中设置的模式(或用逗号分隔的多个模式)。此架构将用于解析此连接上的语句中使用的非限定对象名称。

以下是 JDBC 驱动程序的文档: https ://jdbc.postgresql.org/documentation/head/connect.html