Hibernate + Postgres表和列名敏感问题

5

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

url: jdbc:postgresql://localhost:5432/mydatabase?currentSchema=dbo

Postgres数据库具有大小写混合的表名和列名。 我有以下Hibernate类(其中所有表名和列名均为小写):

@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;
.....
}

数据库表中有以下列(混合大小写):

enter image description here

当我使用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\"") 

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

在Hibernate或PostgreSQL中是否有任何设置可以使表名和列名不区分大小写?有没有任何建议来解决这个问题?


你使用双引号创建了表。这使得表名区分大小写。你必须重新创建该表,而不使用双引号。作为一个经验法则:在SQL中永远不要使用双引号。 - user330315
我在这篇帖子中尝试解释了一个可能的解决方案:https://dev59.com/wq7la4cB1Zd3GeqPcGNs#56793117 - Fırat Küçük
1个回答

8

请尝试将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 注解中还可以添加 schema。例如:@Table(name="table", schema="schemaname")

同时,在 @Column 注解中,name 属性并非必需。

这在我使用 Postgresql 10、Hibernate 5.x 和 Spring Boot 2.1.x 时可行。

祝你好运!


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接