gpt4 book ai didi

java - Postgres UUID 和 Hibernate → 未找到列

转载 作者:行者123 更新时间:2023-12-02 09:46:29 25 4
gpt4 key购买 nike

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

native 查询一切正常,但当我尝试使用 HQL 时,它告诉我找不到 id 列:列 huser0_.id 不存在

这是存储库的代码:

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)

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

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

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

<小时/>

一些更多信息来理解问题并检查我是否有任何拼写错误。 :)

表 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
);

实体类:

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 字段上尝试了各种选项,但没有一个适用于 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. 不要使用保留关键字,将表名称更改为其他名称。

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

  3. 将行 hibernate.globally_quoted_identifiers=true 添加到您的配置中。我想知道为什么默认情况下它不是 true...请参阅 this了解更多详情。

关于java - Postgres UUID 和 Hibernate → 未找到列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56613824/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com