【问题标题】:Hibernate + Postgres table and column name sensitive issueHibernate + Postgres 表和列名敏感问题
【发布时间】:2019-06-20 11:31:04
【问题描述】:

我正在使用 Spring Boot 2.1 + Hibernate 5.x + Postgres 11.x 我的数据库连接字符串:-

网址:jdbc:postgresql://localhost:5432/mydatabase?currentSchema=dbo

Postgres 数据库有混合大小写的表名和列名。 我有如下的休眠类(所有的表和列名都是小写的):-

@Entity
@Table(name = "products")
@Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)
public class Products implements Serializable {
...
@Size(max = 80)
@Column(name = "barcode", length = 80)
private String barcode;

@NotNull
@Size(max = 80)
@Column(name = "name", length = 80, nullable = false)
private String name;

@Column(name = "hidden")
private Boolean hidden = false;
.....
}

并且数据库表具有如下列(混合大小写):-

当我使用 JPA 存储库方法选择所有数据时,hibernate 正在生成以下查询。

select products0_.id as id1_140_, products0_.barcode as barcode2_140_, 
products0_.creation_time as creation3_140_, products0_.hidden as hidden4_140_, 
from dbo.products products0_ limit 10

导致如下错误:-

Caused by: org.postgresql.util.PSQLException: ERROR: relation "products" does not exist
  Position: 449
        at org.postgresql.core.v3.QueryExecutorImpl.receiveErrorResponse(QueryExecutorImpl.java:2440)

即使我使用如下表名:-

@Table(name = "Products") // 与我在数据库中的名称相同

我遇到了同样的错误,因为 postgres 需要为混合大小写名称加上引号,并且在每个类中添加这种更改是很大的痛苦。

如果我使用下面这样的名称,它将起作用:-

@Table(name = "\"Products\"") 

但这是一个非常痛苦的解决方案,它会使我的代码仅依赖于 postgres 数据库。

在 hibernate 或 postgres 中是否有任何设置可以使表和列名不敏感?有什么建议可以解决这个问题吗?

【问题讨论】:

  • 您使用双引号创建了表格。这使得名称case sensitive。您必须在不使用双引号的情况下重新创建该表。根据经验:不要在 SQL 中使用双引号
  • 我试图在那篇文章中解释一个可能的解决方案:stackoverflow.com/a/56793117/159837

标签: java postgresql hibernate


【解决方案1】:

尝试如下更改 application.properties :

spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.PostgreSQL95Dialect
spring.jpa.hibernate.naming.implicit-strategy=org.hibernate.boot.model.naming.ImplicitNamingStrategyLegacyJpaImpl
spring.jpa.hibernate.naming.physical-strategy= org.hibernate.boot.model.naming.PhysicalNamingStrategyStandardImpl
spring.jpa.properties.hibernate.globally_quoted_identifiers=true

顺便说一句,在@Table 中也添加架构。即@Table(name="table", schema="schemaname") 此外,不需要在 @Column (name ="xx") 中。

这对我来说适用于 Postgresql 10、Hibernate 5.x 和 Spring Boot 2.1.x

祝你好运

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-03-01
    • 2010-12-11
    • 1970-01-01
    • 1970-01-01
    • 2023-04-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多