簡體   English   中英

無法添加或更新子行:外鍵約束失敗 - hibernate 中的雙向映射

[英]Cannot add or update a child row: a foreign key constraint fails - Bidirectional mapping in hibernate

嗨,我對 JPA 有疑問...

D B:

數據庫

Java 類(省略不相關的字段):

用戶:

@Entity
public class User{
    @Id
    private int iduser;

    //bi-directional many-to-one association to UserInfo
    @OneToMany(mappedBy="user", cascade= {CascadeType.ALL}, fetch=FetchType.EAGER)
    private List<UserInfo> userInfos;
}

用戶信息:

@Entity
@Table(name="user_info")
public class UserInfo {
    @Id
    @Column(name="iduser_info")
    private int iduserInfo;

    //bi-directional many-to-one association to User
    @ManyToOne  
    private User user;
}

目前,當我嘗試這樣做時(我再次省略了設置不相關的字段):

User u = new User();            
UserInfo info = new UserInfo();
u.addUserInfo(info);

em.persist(u); // save user

我收到此錯誤:

Cannot add or update a child row: a foreign key constraint fails (`webstore`.`user_info`, CONSTRAINT `fk_user_info_user` FOREIGN KEY (`user_iduser`) REFERENCES `user` (`iduser`) ON DELETE NO ACTION ON UPDATE NO ACTION)

我整天都在敲我的頭,我想不通......我也在這里搜索過解決方案,但他們都建議這個錯誤表明我想在沒有輸入 user_iduser 值的情況下輸入 UserInfo,但即使我添加這之前堅持:

info.setUser(u);

它仍然不起作用-級聯甚至支持雙向映射嗎? 所需的效果是應插入用戶,然后在引用原始用戶之后插入列表中的所有用戶信息。 我怎樣才能做到這一點?

我不想做

SET foreign_key_checks = 0/1;

每次=(

嘗試:

@ManyToOne
@JoinColumn(name="user_iduser", nullable=false)
private User user;

然后看看這是否有效。 我假設在user_info表中,您的RDBMS中的user_id字段為NOT NULL 此外,由於它是雙向的,你將不得不setXXXUserInfoUser

User u = new User();            
UserInfo info = new UserInfo();
info.setUser(u);
u.addUserInfo(info);

em.persist(u); // save user

更新:您確定要為UserUserInfo指定ID嗎? 看起來ID沒有設置,因此沒有引用將UserInfo鏈接到User

如果ID是AUTO_INCREMENT ,則在@Id注釋后添加以下內容:

@GeneratedValue(strategy=GenerationType.IDENTITY)

這在我的示例中對我有用,我創建了書籍和圖書館。

@Entity
@Table(name = "book")
public class Books{ 
        @Id
        private int library_id;
        private String libraryname;

        //add getters and setters bellow
}

@Entity
@Table(name = "library")
public class Book {
        @Id
        private int book_id;
        private String book_title;

        @JsonIgnore
        @ManyToOne
        @JoinColumn(name="library_id" , nullable = false)
        @OnDelete(action = OnDeleteAction.CASCADE)
        private Library library;

       //set getters and setters
 }

在控制器中我使用了這種方法

@RequestMapping(value = "/{libraryId}/book", method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_VALUE)
public Book createBook(@PathVariable(value = "libraryId") Integer libraryId, @RequestBody Book book) {

        List<Book> books = new ArrayList<Book>();
        Library author1 = new Library();

        Optional<Library> byId = LibraryRepository.findById(libraryId);


        Library author = byId.get();

        book.setLibrary(author);

        Book book1 = bookRepository.save(book);
        books.add(book1);
        author1.setBooks((List<Book>) books);

        return book1;
}

我也有這個錯誤,通過在 iduser 頂部添加@GeneratedValue(strategy = GenerationType.IDENTITY)注釋來修復此錯誤,並且您必須有外鍵 CASCADE ON DELETE、UPDATE。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM