[英]Springboot 2 CrudRepository.save always throws ConstraintViolationException
我已經在項目中將Springboot版本從1.4.3.RELEASE遷移到2.1.0.RELEASE。 之后,CrudRepository.save()總是拋出org.hibernate.exception.ConstraintViolationException:無法執行語句。
這是我在日志中看到的內容:
o.h.e.j.s.SqlExceptionHelper[m: SQL Error: 1062, SQLState: 23000
o.h.e.j.s.SqlExceptionHelper[m: Duplicate entry '11' for key 'PRIMARY'
o.h.i.ExceptionMapperStandardImpl[m: HHH000346: Error during managed flush [org.hibernate.exception.ConstraintViolationException: could not execute statement
這是我要保存的實體。
@Getter
@Setter
@Entity
@Table(name = "project_m")
public class Project {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "id", nullable = false)
private Long id;
@Column(name = "name" , nullable = false)
private String name;
//other fields
}
ConstraintViolationException
的原因是違反了SQL數據庫的主鍵約束。在SQL中,主鍵是用於標識記錄的唯一鍵,當您嘗試向主列中插入重復值時,數據庫將引發異常。 反過來,它由休眠狀態傳入並傳遞給您的代碼,這就是此異常的原因。
從Springboot 1.4.3.RELEASE到2.1.0.RELEASE Hibernate版本從5.0更新到5.3。
從Hibernate 5.0版開始,Hibernate解釋AUTO生成類型的方式已更改
如果使用strategy="AUTO"
,則Hibernate將生成一個名為hibernate_sequence
的表,以提供ID序列的下一個數字。 您可能忘記了將自動增量功能添加到表的PK中。
解決的另一種方法是使用帶有strategy="AUTO"
注釋
@Id
@GeneratedValue(
strategy= GenerationType.AUTO,
generator="native"
)
@GenericGenerator(
name = "native",
strategy = "native"
)
private Long id;
您可以使用生成策略strategy="IDENTITY"
來強制使用SQL中可用的AutoIncrement功能,並避免創建表。
請檢查這里以獲得更多見解
我通過在hibernate_sequence
表中設置一個較大的值來解決此問題。 我看到重復的主鍵錯誤中的主鍵值是從名為hibernate_sequence
的表生成的。
當我們在實體中設置GenerationType.AUTO時,Hibernate將基於Hibernate方言選擇生成策略。 在舊版本中,Hibernate選擇GenerationType.IDENTITY
作為MySQL數據庫的默認值。
現在選擇使用數據庫表生成主鍵的GenerationType.TABLE
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.