我有以下实体:
@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
。但是当我尝试这个时:
User user = new User();
user.setBankAccount(new BanckAccount());
userRepository.save(user);
我有这个异常(exception):
org.hibernate.PropertyValueException: not-null property references a null or transient value : org.company.models.User.bankAccount
保存级联不会传播,我必须在将其设置给用户之前保存 bankAccount
。我错过了什么,我应该审查我的协会吗?
谢谢
最佳答案
您在关系的错误一侧指定了 mappedBy。它应该在反向(非拥有)侧指定。由于您希望用户保存帐户,因此用户必须是所有者。
关于java - 双向@OneToOne级联问题JPA/Hibernate/Spring-Data,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50179610/