spring - 保存后的 JPA 查询不返回数据库生成的字段

标签 spring postgresql hibernate jpa

我正在尝试将此模型保存到数据库中,然后检索我刚刚保存的内容。除了数据库生成的 UUID 字段外,每个字段都被检索。

@Entity
@Table(name = "usertoken")
public class UserToken implements Serializable
{
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Integer id;
    
    @Column(name = "token", insertable = false, updatable = false, nullable = false)
    private UUID token;
    
    @ManyToOne(fetch = FetchType.EAGER)
    @JoinColumn(name="usersid", nullable=false)
    private User user;
    
    @Column(name = "expiration", updatable = false, nullable = false)
    private LocalDateTime expiration;
我从服务中保存 token
token = tokenRepository.save(token);
生成此 SQL
Hibernate: 
    insert 
    into
        usertoken
        (expiration, usersid) 
    values
        (?, ?)
下一条语句获取 token
token = tokenRepository.findByUser(user);
我看到 SQL 选择包含 token 字段
Hibernate: 
    select
        usertoken0_.id as id1_8_,
        usertoken0_.expiration as expirati2_8_,
        usertoken0_.token as token3_8_,
        usertoken0_.usersid as usersid4_8_ 
    from
        usertoken usertoken0_ 
    where
        usertoken0_.usersid=?
...但返回的对象的每个字段都填充了 token 。数据库在 token 列中有一个值。
我不知道为什么它会填充除一个之外的每个领域。
这是有问题的表格:
CREATE TABLE public.usertoken
(
    id integer NOT NULL GENERATED ALWAYS AS IDENTITY ( INCREMENT 1 START 1 MINVALUE 1 MAXVALUE 2147483647 CACHE 1 ),
    usersid integer NOT NULL,
    token uuid NOT NULL DEFAULT uuid_generate_v1(),
    expiration timestamp without time zone NOT NULL,
    CONSTRAINT "usertoken_pkey" PRIMARY KEY (id)
)
我忘了补充一点,当我稍后查询时,找到了 token 并且正确填充了 UUID 字段。那么 JPA 缓存有什么奇怪的吗?插入后 hibernate 是否会忽略数据库 DEFAULT 列值?
tokenRepository.findByToken(UUID.fromString(userToken));

Hibernate: 
    select
        usertoken0_.id as id1_8_,
        usertoken0_.expiration as expirati2_8_,
        usertoken0_.token as token3_8_,
        usertoken0_.usersid as usersid4_8_ 
    from
        usertoken usertoken0_ 
    where
        usertoken0_.token=?

最佳答案

  • 您必须通知 hibernate 该字段正在由数据库生成。所以添加以下内容:
  •     @org.hibernate.annotations.Generated(value = GenerationTime.INSERT)
        @Column(name = "token", insertable = false, 
                updatable = false, nullable = false)
        private UUID token;
    
  • 您还将看到 hibernate 问题 select仅针对 insert 之后的那一列
  • 关于spring - 保存后的 JPA 查询不返回数据库生成的字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62941966/

    相关文章:

    java - 使用Spring+dbcp刷新数据源

    linux - 在部署脚本中查找已安装的包时,是否应该检查所有可能的路径?

    python - SQLAlchemy,声明式,PostgreSQL : cannot create tables

    java - 复合键类关系→错误: not mapped to a single property

    mysql - 更新 MySQL 表中的排名

    java - Spring 3 安全和相关重定向 URL

    java - 在Spring Boot中使用hibernate-types-52时如何禁用Hypersistence横幅?

    database - 如何连接到 postgresql google cloud sql 实例?需要使用 pg_restore 命令导入 postgresql 转储

    hibernate - 如何在gorm-hibernate中使用hasMany属性保存域

    java - 业务逻辑(那是什么?)真正存在于何处以及如何使用 Spring 做到这一点?