[英]Hibernate not respecting MySQL auto_increment primary key field
[英]JPA overwrite record with auto_increment primary key
我已經搜索過,但找不到我。 我有一個類似這樣的實體類:
@Entity
public class Report {
@Id @GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id")
private int id;
@Column(name = "descrizione")
private String descrizione = null;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getDescrizione() {
return descrizione;
}
public void setDescrizione(String descrizione) {
this.descrizione = descrizione;
}
}
並用auto_increment pk將表插入mysql db。 但是我不知道為什么auto_increment僅在啟動Web服務時才能工作。 以后,休眠只覆蓋最后一條記錄,而無需使用自動遞增的主鍵創建新記錄。
進入application.properties,我有以下配置:
spring.jpa.hibernate.ddl-auto=none
spring.datasource.url=jdbc:mysql://localhost:3306/civicsense?serverTimezone=UTC
spring.datasource.username=root
spring.datasource.password=AAAAAAA
一些幫助將不勝感激
您需要更改:
@GeneratedValue(strategy = GenerationType.IDENTITY)
對於
@GeneratedValue(strategy = GenerationType.AUTO)
並在application.properties中使用:
spring.jpa.hibernate.ddl-auto=update
首先,將int更改為Long。 而且您可以省略該策略,因為對於MySQL GenerationType.IDENTITY
與GenerationType.AUTO
相同,這等同於只添加@GeneratedValue
。
@Id @GeneratedValue
private Long id;
同樣,您的問題可能是您添加實體的方式。 在這種情況下,您可能要使用saveAndFlush()
,因為更改將立即在此命令中刷新到DB,這可能會阻止您的問題,因為您的實際方法可能未按時提交。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.