双向@OneToOne级联问题JPA / Hibernate / Spring-Data

时间:2018-05-04 16:39:40

标签: java hibernate spring-data-jpa one-to-one cascading

我有以下实体:

@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); 。但是当我尝试这个时:

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

我有这个例外:

bankAccount

保存级联不会传播,我必须先保存Total_fee AS (DATEDIFF(DAY, Date_of_Rent_End_Due, Date_of_Rent_End)) * @fee_per_day ,然后再将其设置为用户。我错过了什么,我应该检讨一下我的关联吗? 感谢

3 个答案:

答案 0 :(得分:2)

您在关系的错误一侧指定mappedBy。它应该在反向(非拥有)方面指定。由于您希望用户保存帐户,因此用户必须是所有者。

答案 1 :(得分:1)

您的mappedBy应该位于您想要先保存的子实体中。所以这里映射的应该是BankAccount另外您应该在父实体中使用@JoinColumn,因此子的外键可以存储在父表中。例如:

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

请参阅类似示例here.

答案 2 :(得分:0)

要完成此帖子,从子级到父级的级联操作在这种情况下@OneToOne(optional=false,mappedBy=...)起作用。如果我们在子级中设置optional=false,则级联似乎有效(至少Cascade.PERSIST)。

相关问题