双向@OneToOne 级联问题 JPA/Hibernate/Spring-Data [英] Bidirectional @OneToOne cascade issue JPA/Hibernate/Spring-Data

查看:58
本文介绍了双向@OneToOne 级联问题 JPA/Hibernate/Spring-Data的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下实体:

@Entity
public class User implements Serializable {

   private String username;

   @OneToOne( optional = false, mappedBy = "user", orphanRemoval = true, fetch = FetchType.LAZY, cascade = CascadeType.ALL )
   private BankAccount bankAccount;
   //.....
}

还有:

@Entity
public class BankAccount implements Serializable {

    @OneToOne( optional = false, fetch = FetchType.LAZY )
    @JoinColumn( name = "user", unique = true, referencedColumnName = "username" )
    private User user;
    //...
}

对我来说,我希望我是对的,User 实体是父实体,因此我可以将其操作级联到 BankAccount.但是当我尝试这个时:

For me, I hope I'm right, User entity is the parent so I can cascade its operations to BankAccount. But when I try this :

User user = new User();
user.setBankAccount(new BanckAccount());
userRepository.save(user);

我有这个例外:

org.hibernate.PropertyValueException: not-null property references a null or transient value : org.company.models.User.bankAccount

保存级联不会传播,我必须在将它设置给用户之前保存 bankAccount.我是否遗漏了什么,我应该检查我的协会吗?谢谢

The save cascading is not propagated and I have to save bankAccount before setting it to the user. Am I missing something, should I review my association? Thanks

推荐答案

你的 mappedBy 应该在你想要先保存的子实体中.所以这里mapped by应该在BankAccount中.另外您应该在父实体中使用@JoinColumn,这样子实体的外键就可以存储在父表中.例如:

Your mappedBy should be in child entity, which you want to be saved first. So here mapped by should be in BankAccount. Also You should use @JoinColumn in parent entity, so the foreign key of child can be stored in parent table. For example:

@Entity
public class User implements Serializable {

   private String username;

   @OneToOne( optional = false, orphanRemoval = true, fetch = FetchType.LAZY, cascade = CascadeType.ALL )
   @JoinColumn(name = "bank_account_id")
   private BankAccount bankAccount;
   //.....
}

BankAccount中:

@Entity
public class BankAccount implements Serializable {

    @OneToOne( optional = false, fetch = FetchType.LAZY, mappedBy = "bankAccount")
    private User user;
    //...
}

看类似的例子 此处.

这篇关于双向@OneToOne 级联问题 JPA/Hibernate/Spring-Data的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆