【问题标题】:Problem while persisting the existing parent object into the child object将现有父对象持久保存到子对象时出现问题
【发布时间】:2020-04-26 09:36:55
【问题描述】:

我有一个带有预填充数据的现有表 Action,我正在尝试保存一个对象 Stop,它具有 Action.Id 作为外键。下面是我尝试过的代码。但是在 Stop 表中,即使没有错误,引用也没有保存。

  public class Stop {

    @OneToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "ACTION_ID", updatable = false, insertable = false)
    private Action action;
}
public class Action {

    @Id
    @Column(name = "ACTION_ID")
    private String actionId;

    @OneToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "ACTION_ID")
    private Stop stops;
}

我尝试显式调用Optional<Action> action = actionRepo.findByActionId("ARRIVE") 并设置为停止对象。但它没有与参考一起保存。

【问题讨论】:

    标签: java hibernate spring-boot spring-data-jpa hibernate-mapping


    【解决方案1】:

    为 JPA 对象设置新值后,您需要调用 save

    Optional<Action> action = actionRepo.findByActionId("ARRIVE");
        if (action.isPresent()){
        actionRepo.save(action.get().setActionName("balal"));
    }
    

    【讨论】:

      【解决方案2】:

      我认为您需要从 Action 类中删除 @JoinColumn 注释。您通常不需要两边都使用它。

      public class Stop {
          @OneToOne(fetch = FetchType.LAZY)
          @JoinColumn(name = "ACTION_ID", updatable = false, insertable = false)
          private Action action;
      }
      
      public class Action {
          @Id
          @Column(name = "ACTION_ID")
          private String actionId;
      
          @OneToOne(fetch = FetchType.LAZY)
          private Stop stops;
      }
      

      【讨论】:

      • 通过移除 updatable = false, insertable = false 和 @OneToOne(mappedBy="action") private Stop 停止解决它;
      猜你喜欢
      • 1970-01-01
      • 2011-07-25
      • 2010-11-25
      • 1970-01-01
      • 2012-03-31
      • 2011-07-26
      • 2014-11-13
      • 2012-10-24
      • 1970-01-01
      相关资源
      最近更新 更多