Postgres UUID 和 Hibernate → 找不到列

Postgres UUID and Hibernate → no column found

我在使用 Postgres UUID 类型、java.util.UUID 和 Hibernate 时遇到问题。

本机查询一切正常,但当我尝试使用 HQL 时,它告诉我找不到 id 列:column huser0_.id does not exist.

这是存储库的代码:

import com.xobotun.common.HUser;
import java.util.UUID;

@org.springframework.stereotype.Repository
public interface ReadOnlyUserRepository extends Repository<HUser, UUID> {
    // @Query("select u from HUser u where u.id = :id")
    @Query(value = "select * from \"user\" where id = :id", nativeQuery = true)
    HUser getById(@Param("id") UUID id);

}

这样它打印出预期的

HUser(id=fbd3c9e2-8fa4-11e9-bc42-526af7764f64, name=test, about=test, isPermabanned=false, created=2019-06-15T19:37:30.503, lastActive=2019-06-15T19:37:33.512)

但是当注释掉本机查询并使用 HQL 时,它突然停止工作:

org.postgresql.util.PSQLException: ERROR: column huser0_.id does not exist

有人遇到过这样的问题吗?谢谢。


一些更多的信息来理解这个问题并检查我是否有错别字。 :)

Table DDL:

CREATE TABLE "user" (
  id             UUID                    NOT NULL PRIMARY KEY,
  name           TEXT                    NOT NULL,
  is_permabanned BOOLEAN DEFAULT FALSE   NOT NULL,
  created        TIMESTAMP DEFAULT now() NOT NULL,
  last_active    TIMESTAMP,
  about          TEXT
);

实体class:

package com.xobotun.common;

import lombok.Data;

import javax.persistence.*;
import java.time.LocalDateTime;
import java.util.UUID;

@Data
@Entity
@Table(name = "user")
public class HUser {
    @Id
    @Column(name = "id") //, columnDefinition = "uuid", updatable = false)
//    @Type(type="pg-uuid")
    private UUID id;

    @Column(name = "name")
    private String name;

    @Column(name = "about")
    private String about;

    @Column(name = "is_permabanned")
    private Boolean isPermabanned;

    @Column(name = "created")
    private LocalDateTime created;

    @Column(name = "last_active")
    private LocalDateTime lastActive;
}

如您所见,我在 id 字段上尝试了各种选项,但其中 none 可以使用 HQL 查询。

Java 版本是 11,PostgreSQL 也是 11,这里是相关的依赖项:

dependencies {
    compile 'org.springframework.data:spring-data-jpa:2.1.5.RELEASE'
    compile 'javax.persistence:javax.persistence-api:2.2'
    compile 'com.vladmihalcea:hibernate-types-52:2.4.4'

    implementation 'org.hibernate:hibernate-core:5.4.3.Final'
    implementation 'org.postgresql:postgresql:42.2.5.jre7'
}

此外,我尝试了这些问题的解决方案,但它们没有帮助:1 2 3 4

UPD1: 这是 Hibernate 在查询失败时生成的 SQL:

    select
        huser0_.id as id1_0_,
        huser0_.about as about2_0_,
        huser0_.created as created3_0_,
        huser0_.is_permabanned as is_perma4_0_,
        huser0_.last_active as last_act5_0_,
        huser0_.name as name6_0_ 
    from
        user huser0_ 
    where
        huser0_.id=?

感谢@JBNizet 的友好评论,我发现问题不在于奇怪的 UUID 行为,而是 Hibernate 默认情况下不会转义标识符。

这个问题实际上有三个简单的解决方案:

  1. 不要使用保留关键字,将 table 名称更改为其他名称。

  2. 手动转义 table 名称(如 HUser.java 中的 @Table(name = "\"user\""))。

  3. 将行 hibernate.globally_quoted_identifiers=true 添加到您的配置中。我想知道为什么默认情况下它不是 true...有关详细信息,请参阅 this