【问题标题】:JPA association table is not deletableJPA关联表不可删除
【发布时间】:2010-03-19 21:03:42
【问题描述】:

我对 JPA (EclipseLink) 有疑问。 我无法删除关联表。情况是这样的:

  • Product 1:n 到 ProductResource
  • 资源 1:n 到 ProductResource

我首先设置了ProductResource的产品和资源属性。如果我然后尝试删除 ProductResource 对象,则没有任何反应(没有生成 sql - 没有例外)。如果我注释掉 ProductResource 中的两个 OneToMany 注释,我可以删除该对象。我也可以在未设置产品和资源属性时删除对象。如果我仅注释掉 ressource 属性上方的注释,则 ProductResource 对象会在删除产品对象时被删除(cascade=CascadeType.ALL)。我希望有人能给我一个提示。谢谢。

产品资源:

public class ProductResource implements Serializable {
 @ManyToOne(fetch=FetchType.EAGER, cascade=CascadeType.MERGE)
 private Product product;

 @ManyToOne(fetch=FetchType.EAGER, cascade=CascadeType.MERGE)
 private Resource resource;

产品:

public class Product implements Serializable {

 @OneToMany(mappedBy="product", fetch=FetchType.EAGER, cascade=CascadeType.ALL)
 private List<ProductResource> productResources = new ArrayList<ProductResource>();

资源:

public class Resource implements Serializable {

 @OneToMany(mappedBy="resource", fetch=FetchType.EAGER, cascade=CascadeType.ALL)
 private List<ProductResource> productResources = new ArrayList<ProductResource>();

问候马塞尔

【问题讨论】:

    标签: jpa eclipselink


    【解决方案1】:

    其实有3种解决方案:

    1) 在删除 ProductResource 对象之前删除孤儿。 ProductResource 没有被删除的原因是系统中仍然存在引用它们的对象。

    2) 删除孤立对象中对 ProductResource 对象的引用。原因同上。

    3) 使用 JPA 注释将 Product 和 Resource 对象设置为 @PrivateOwned。如果孤儿存在,这将导致它们被自动删除。这是您可能希望或可能不希望为您自动完成的行为。造成这种情况的原因可能是因为 Product 或 Resource 对象不需要对 ProductResource 的引用即可存在。这取决于您的设计。

    【讨论】:

    • 非常感谢您的详细解释。起初 JPA 看起来很容易使用。魔鬼在细节中。像你这样的人花时间帮助像我这样的新手真是太好了。问候马塞尔
    【解决方案2】:

    以下是解决方案:

    产品类别

    @PrivateOwned
    @OneToMany(mappedBy="product", fetch=FetchType.EAGER, cascade=CascadeType.ALL)
    private List<ProductResource> productResources = new ArrayList<ProductResource>();
    

    资源类

    @PrivateOwned
    @OneToMany(mappedBy="resource", fetch=FetchType.EAGER, cascade=CascadeType.ALL)
    private List<ProductResource> productResources = new ArrayList<ProductResource>();
    

    @PrivateOwned 是新的...

    马塞尔

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多