java 无法添加或更新子行:外键约束失败 - 休眠中的双向映射

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/29518396/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-02 15:24:53  来源:igfitidea点击:

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

javahibernatejakarta-eejpa

提问by BizzyDizzy

Hi I have a problem with JPA...

嗨,我有 JPA 问题...

DB:

D B:

Database

数据库

Java classes (irrelevant fields are ommited):

Java 类(忽略不相关的字段):

User:

用户:

@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;
}

UserInfo:

用户信息:

@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;
}

Currently when I try to do this (again I omitted setting irrelevant fields):

目前,当我尝试这样做时(我再次省略了设置不相关的字段):

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

em.persist(u); // save user

I get this error:

我收到此错误:

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)

I have been banging my head all day and I can't figure it out... I have also searched for solutions here but they all suggest that this error shows that I want to enter UserInfo without user_iduser value entered, but even if I add this before persist:

我整天都在敲我的头,我想不通......我也在这里搜索了解决方案,但他们都表明这个错误表明我想在没有输入 user_iduser 值的情况下输入 UserInfo,但即使我添加这之前坚持:

info.setUser(u);

it still doesn't work - is bidirectional mapping even supported with cascading? The desired effect is that User should be inserted and then all the UserInfos in the list after it refering the original User. How can I achieve that?

它仍然不起作用 - 级联甚至支持双向映射吗?预期的效果是应该插入 User,然后在它引用原始 User 之后插入列表中的所有 UserInfo。我怎样才能做到这一点?

I don't want to do

我不想做

SET foreign_key_checks = 0/1;

everytime =(

每次=(

回答by Buhake Sindi

Try:

尝试:

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

Then see if this works. I'm assuming that in user_infotable, the user_idfield is NOT NULLin your RDBMS. Also, since it's bidirectional, you will have to setXXXon UserInfoand User.

然后看看这是否有效。我假设在user_info表中,该user_id字段NOT NULL在您的 RDBMS 中。此外,由于它是双向的,因此您必须setXXX打开UserInfoUser

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

em.persist(u); // save user


Update:Are you sure you're specifying an ID for both Userand UserInfo? It looks like the ID is not set hence there is no reference to link UserInfoto User.

更新:您确定要为User和指定 IDUserInfo吗?它看起来像没有设置ID,因此有链接没有提及UserInfoUser

If the ID are AUTO_INCREMENT, then add the following after @Idannotation:

如果 ID 是AUTO_INCREMENT,则在@Id注释后添加以下内容:

@GeneratedValue(strategy=GenerationType.IDENTITY)

回答by pradeep karunathilaka

this is worked for me in my example , i created books and library.

这在我的示例中对我有用,我创建了书籍和图书馆。

@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
 }

in controller i used this method

在控制器中我使用了这种方法

@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;
}