【问题标题】:Hibernate JPA UniDirectional OneToOne Join - Updating a null foreign key after been inserted as nullHibernate JPA UniDirectional OneToOne Join - 在插入为空后更新空外键
【发布时间】:2020-10-10 18:47:10
【问题描述】:

我正在尝试在 Spring-Boot Web 应用程序中使用 JPA Hibernate 使用单向 OneToOne 映射来实现以下场景:

  1. 使用 CrudRepository.save() 在实体中插入记录 (EntityTwo) 与另一个实体 (EntityOne) 的外键为 null
  2. 更新插入的 记录使用 CrudRepository.save() 将外键设置为非空值

实体一看起来像这样:

@Entity
public class EntityOne implements Serializable {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "entity_one_id", updatable = false, nullable = false)
    private Long id;

}

实体二如下所示:

@Entity
public class EntityTwo implements Serializable {

    @OneToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "entity_one_id")
    private EntityOne entityOne;
}

这就是保存调用的样子

第一次保存调用:

EntityTwo entityTwo = new EntityTwo();
entityTwoRepository.save(entityTwo);

第二次保存调用:

EntityOne entityOne = entityOneRepository.getByEntityOneId(1); // this results in a not-null value
EntityTwo entityTwo = new EntityTwo();
entityTwo.setEntityOne(entityOne);
entityTwoRepository.save(entityTwo);

第二次调用后,我希望在 EntityTwo 中设置外键,但事实并非如此。如果我做错了什么,或者是否有更好的/其他方法可以使用 Spring-Boot JPA 实现这一点,请告诉我

【问题讨论】:

    标签: java spring-boot hibernate jpa


    【解决方案1】:

    你应该级联操作。

    @Entity
    public class EntityOne implements Serializable {
    
        @Id
        @GeneratedValue(strategy = GenerationType.IDENTITY)
        @Column(name = "entity_one_id", updatable = false, nullable = false)
        private Long id;
    
    }
    
    @Entity
    public class EntityTwo implements Serializable {
    
        @OneToOne(fetch = FetchType.LAZY, cascade = CascadeType.ALL)
        @JoinColumn(name = "entity_one_id")
        private EntityOne entityOne;
    }
    

    试试;

    EntityOne entityOne = new EntityOne();
    EntityTwp entityTwo = new EntityTwo();
    entityTow.setEntityOne(entityOne);
    entityTwoRepository.save(entityTwo);
    

    【讨论】:

      猜你喜欢
      • 2019-04-16
      • 2021-08-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-03-26
      • 1970-01-01
      • 1970-01-01
      • 2012-06-05
      相关资源
      最近更新 更多