gpt4 book ai didi

java - JPA - INSERT 后的 PK 属性问题

转载 作者:行者123 更新时间:2023-12-02 08:49:47 25 4
gpt4 key购买 nike

JPA( hibernate 提供程序)和 Postgres 11

我的 Id 属性有此配置(它是单个列/属性 PK)。

由于某种原因,在对该表执行 INSERT 操作后,JPA 调用

选择 currval('yb.asset_store_id_seq')

我猜(我不确定)这样做是为了刷新新插入实体的 ID,或者可能出于某种类似的原因。

但是不存在这样的序列。我的序列名为 yb.asset_store_seq,我的表为 yb.asset_store。我的实体类是AssetStore

那么...我该如何解决这个问题呢?基本上JPA 不知何故编造了这个序列名称。或者我错过了什么?!

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id", unique = true, nullable = false, insertable=false, updatable=false)
private Integer id;

在数据库级别,序列由表拥有。

这是堆栈跟踪。

    Hibernate: 
select
currval('yb.asset_store_id_seq')
Mar 25, 2020 3:45:02 PM org.hibernate.engine.jdbc.spi.SqlExceptionHelper logExceptions
WARN: SQL Error: 0, SQLState: 42P01
Mar 25, 2020 3:45:02 PM org.hibernate.engine.jdbc.spi.SqlExceptionHelper logExceptions
ERROR: ERROR: relation "yb.asset_store_id_seq" does not exist
Position: 16
Exception in thread "main" javax.persistence.PersistenceException: org.hibernate.exception.SQLGrammarException: could not extract ResultSet


...................


Caused by: org.postgresql.util.PSQLException: ERROR: relation "yb.asset_store_id_seq" does not exist
Position: 16
at org.postgresql.core.v3.QueryExecutorImpl.receiveErrorResponse(QueryExecutorImpl.java:2440)
at org.postgresql.core.v3.QueryExecutorImpl.processResults(QueryExecutorImpl.java:2183)
at org.postgresql.core.v3.QueryExecutorImpl.execute(QueryExecutorImpl.java:308)

最佳答案

首先是 hibernate documentation根本不建议使用 GenerationType.IDENTITY 策略:

It is important to realize that using IDENTITY columns imposes a runtime behavior where the entity row must be physically inserted prior to the identifier value being known.

This can mess up extended persistence contexts (long conversations). Because of the runtime imposition/inconsistency, Hibernate suggests other forms of identifier value generation be used (e.g. SEQUENCE).

There is yet another important runtime impact of choosing IDENTITY generation: Hibernate will not be able to batch INSERT statements for the entities using the IDENTITY generation.

但是如果你不能改变它,并且你使用的是JDBC3+驱动程序和JRE1.4+。我建议明确定义:

<property name="hibernate.jdbc.use_get_generated_keys">true</property>

因为根据this

hibernate.jdbc.use_get_generated_keys (e.g. true or false)

Allows Hibernate to use JDBC3 PreparedStatement.getGeneratedKeys() to retrieve natively-generated keys after insert. You need the JDBC3+ driver and JRE1.4+. Disable this property if your driver has problems with the Hibernate identifier generators. By default, it tries to detect the driver capabilities from connection metadata.

它将可以避免您的问题。

关于java - JPA - INSERT 后的 PK 属性问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60856409/

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