【问题标题】:Bidirectional @OneToOne not work when persisting child without parent在没有父母的情况下坚持孩子时,双向@OneToOne 不起作用
【发布时间】:2018-05-26 16:38:16
【问题描述】:

我有这种情况:

父实体:

@Entity
public class Address {

  @OneToOne( optional = false, targetEntity = User.class, fetch = FetchType.LAZY, orphanRemoval = true )
  @JoinColumn( name = "id_user", referencedColumnName = "id" )
  private User user;

}

子实体:

@Entity
public class User {

   @OneToOne( optional = false, targetEntity = Address.class, mappedBy = "user", fetch = FetchType.LAZY, orphanRemoval = true )
   private Address address;
}

如您所见,双方没有任何级联操作。但是当我保存用户时:

userRepository.save( new User() ); 

它抛出这个异常:

org.springframework.dao.DataIntegrityViolationException: not-null property references a null or transient value : org.company.models.User.address; nested exception is org.hibernate.PropertyValueException: not-null property references a null or transient value : org.company.models.User.address
.............
Caused by: org.hibernate.PropertyValueException: not-null property references a null or transient value : org.company.models.User.address

我只想坚持孩子,应该可以,因为@JoinColumn在父母中,所以我不需要在保存之前设置它。
有人可以澄清我这个问题吗? 非常感谢

【问题讨论】:

    标签: hibernate jpa spring-data-jpa one-to-one bidirectional


    【解决方案1】:

    问题是由于User 和Address 之间的关系被标记为optional=false 这意味着它不能为空。

    因此,您要么需要使用 optional=true 并允许空值,要么在持久化之前在 User 上填充 Address 关系。

    【讨论】:

    【解决方案2】:

    我假设您在地址表中的 id_user 处获得了 null。因为在映射期间,jpa 没有在地址中设置用户的值。您需要在用户实体的地址设置器中明确执行此操作,如下所示。

    public void setAddress(Address address) {
       address.setStudent(this);
       this.address = address;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-03-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-05-13
      相关资源
      最近更新 更多