【问题标题】:Remove fields in embeddable (JPA)删除可嵌入 (JPA) 中的字段
【发布时间】:2015-06-29 14:37:50
【问题描述】:

我正在尝试通过从实体中删除嵌入来删除嵌入中的列表。这不起作用..列表中的所有实体仍在数据库中。

代码:

一切开始的方法:

 //attached entity
 Ship ship = findShip();
 ship.removeItinerary();

船:

@Entity
@Table(name = "SHIP")
public class Ship extends Domain {

   @Embedded
   private Itinerary itinerary;


   public void removeItinerary() {
      this.itinerary = null;
   }    

}

行程:

@Embeddable
public class Itinerary implements Serializable {

   //tried orphanRemoval and cascade but without luck 
   //(since I'm not removing the Ship it's actually logic that it's not working..)
   @OneToMany
   @JoinColumn(name = "SHIP_ID", referencedColumnName = "ID")
   private List<Stop> stops = new ArrayList<>();

}

JPA 2.0

【问题讨论】:

  • 我终于弄清楚我做错了什么。我总是在船上保存一个新的 Itinerary()。错误实际上不在此代码中。对于其他人:orphanRemoval 和 cascade.update 的组合可以解决问题。

标签: java jpa


【解决方案1】:

如果行程已经存入数据库,需要delete它。例如,像

public void removeItinerary() {
   getEntityManager().remove(this.itinerary);
   this.itinerary = null;
}

【讨论】:

  • 不可能删除不是实体的东西。
  • @NeilStockton 很好,但是实体经理不知道。变通办法永远不是解决方案
  • 然后忽略之前的反对票.. 但正如@Gimby 所说的那样.. 这就是我现在要回复的内容^^
【解决方案2】:

在removeItinerary方法调用后尝试合并ship实体。

Ship ship = findShip();
ship.removeItinerary();
em.merge(ship).

【讨论】:

    【解决方案3】:

    我认为这是不可能的...您可以在将行程设置为空之前尝试清除停靠点列表吗...? (结合@JoinColumn 上的 orphanRemoval...)

    !!我从来没有测试过这个... !!

    类似这样的:

    public void removeItinerary() {
       this.itinerary.stops.clear();
       this.itinerary = null;
    }
    

    【讨论】:

    • 我试过没有成功。忘记在问题中提及这一点
    猜你喜欢
    • 2017-09-09
    • 1970-01-01
    • 2014-10-01
    • 1970-01-01
    • 2012-09-20
    • 2010-09-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多