我實作了兩個物體。RuleEntity 和 RestCallEntity 如下所示:
規則物體
@Entity(name = "RuleEntity")
@Table(name = "Rule")
public class RuleEntity {
@Id
@Column(name = ID_COLUMN_NAME, nullable = false)
@GeneratedValue(strategy = AUTO)
private Long id;
@Column(name = "name", nullable = false)
public String name = "";
@OneToMany(targetEntity = RestCallEntity.class, fetch = FetchType.EAGER, cascade = CascadeType.ALL, orphanRemoval = true)
public final Set<RestCallEntity> restCalls = new HashSet<>();
}
RestCallEntity
@Entity(name = "RestCallEntity")
@Table(name = "RestCall")
public class RestCallEntity
@Id
@Column(name = ID_COLUMN_NAME, nullable = false)
@GeneratedValue(strategy = AUTO)
private Long id;
@Column(name = "name", nullable = false)
public String name = "";
}
我在 json 端點中收到一條規則。比我將收到的 json 規則轉換為 RuleEntity 并呼叫
getEntityManager().merge(ruleEntity);
當我只是更改規則的名稱時,更新作業正常。但是當我更改它的名稱時,它看起來像休眠嘗試創建一個新的 restcall,即使它已經有一個 ID。我得到以下例外。
引起:org.postgresql.util.PSQLException:錯誤:重復鍵值違反唯一約束?rule_restcall_pkey?詳情:key ?(ruleentity_id, restcalls_id)=(45, 49)? 已經存在。在 org.postgresql.core.v3.QueryExecutorImpl.receiveErrorResponse(QueryExecutorImpl.java:2675) 在 org.postgresql.core.v3.QueryExecutorImpl.processResults(QueryExecutorImpl.java:2365) 在 org.postgresql.core.v3.QueryExecutorImpl.execute (QueryExecutorImpl.java:355) 在 org.postgresql.jdbc.PgStatement.executeInternal(PgStatement.java:490) 在 org.postgresql.jdbc.PgStatement.execute(PgStatement.java:408) 在 org.postgresql.jdbc.PgPreparedStatement。在 io.agroal.pool.wrapper.PreparedStatementWrapper.executeUpdate(PreparedStatementWrapper.
uj5u.com熱心網友回復:
所以我終于弄清楚這可能是由equals/hashcode方法的實作引起的。我將equals方法更改為僅檢查id,將hashcode方法更改為僅回傳id的hashcode。現在更新作業正常。
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/459056.html
標籤:爪哇 PostgreSQL 休眠 jpa 一对多
