亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

主鍵上的 JPA @AutoGenerate 對嵌套實體使用父序列/自動增量

主鍵上的 JPA @AutoGenerate 對嵌套實體使用父序列/自動增量

www說 2023-06-28 15:53:18
在我的 Spring Boot 應用程序中,我試圖保存一個具有一些具有一對多關系的嵌套實體的實體。我使用 JPA 和 Hibernate 將它們保存到 MySQL 數據庫。在主鍵上,我使用@GeneratedValue(strategy = GenerationType.AUTO)onLong自動為新實體創建值。這工作了一段時間,但是最近我在嘗試保存實體時遇到錯誤:java.sql.SQLIntegrityConstraintViolationException: Duplicate entry '282' for key 'PRIMARY'這就是我的實體的樣子:Question.java@Entity@Table(name = "question")public class Question {    private Long id;    private List<Answer> answers;    // other fields    @Id    @GeneratedValue(strategy = GenerationType.AUTO)    public Long getId() { return id; }    public void setId(Long id) { this.id = id; }    @OneToMany(mappedBy = "question", cascade = CascadeType.ALL, orphanRemoval = true)    public List<Answer> getAnswers() { return answers; }    public void setAnswers(List<Answer> answers) { this.answers = answers; }}Answer.java@Entity@Table(name = "answer")public class Answer {    private Long id;    private Question question;    // other fields    @Id    @GeneratedValue(strategy = GenerationType.AUTO)    public Long getId() { return id; }    public void setId(Long id) { this.id = id; }    @ManyToOne    @JoinColumn(name = "question_id")    public Question getQuestion() { return question; }    public void setQuestion(Question question) { this.question = question; }}存儲庫很簡單:public interface QuestionRepository extends JpaRepository<Question, Long>{ ... }現在假設我通過 Web 表單添加一個新問題,包括 4 個答案。當調用存儲庫時,就像:questionRepository.save(question);經過一番調查后,Hibernate 似乎正在使用question實體表中的自動增量值answers,但該值不起作用,因為它已經存在。
查看完整描述

1 回答

?
MMTTMM

TA貢獻1869條經驗 獲得超4個贊

由于 MySQL 本身不支持序列,因此使用 @GenerateValue(strategy = GenerationType.AUTO) 時可能會出現此問題。

使用以下解決方法來生成 id。

@Id@GeneratedValue(
????strategy=?GenerationType.AUTO,
????generator="native"
)
@GenericGenerator(
????name?=?"native",
????strategy?=?"native"
)
查看完整回答
反對 回復 2023-06-28
  • 1 回答
  • 0 關注
  • 188 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號