【问题标题】:JPA empty tables and join tablesJPA 空表和连接表
【发布时间】:2010-09-23 12:23:28
【问题描述】:

我知道 truncate 不被支持,所以我做了一个 Delete from table - 这很好用,但连接表没有这样清理。示例:

Delete from Product;
Delete from Service;

两者都是空的,表service_product仍然被填满。是否有机会在没有原始 sql 的情况下清理我的连接表?

示例实体

public class Service implements Serializable {
    private static final long serialVersionUID = 4520872456865907866L;
    // seam-gen attributes (you should probably edit these)

    @EmbeddedId
    private ServiceId id;

    @Length(max = 255)
    private String servicename;

    @Column(columnDefinition = "text")
    private String highlightsText;
    @Column(columnDefinition = "text")
    private String detailsText;
    @Column(columnDefinition = "text")
    private String productText;
    @Column(columnDefinition = "text")
    private String dataText;

    @ManyToMany(mappedBy = "services")
    private Set<Machine> machines;

    @OneToMany(targetEntity = ServiceDownload.class, cascade = { CascadeType.ALL }, fetch = FetchType.LAZY)
    private List<ServiceDownload> serviceDownloads;

    @OneToMany(targetEntity = ProductSpecial.class, cascade = { CascadeType.ALL })
    private List<ProductSpecial> productSpecials;

    @OneToOne(cascade = { CascadeType.ALL })
    private ServicePicture servicePicture;
...
}

【问题讨论】:

标签: java hibernate jpa


【解决方案1】:

您应该添加 @OnDelete(action=OnDeleteAction.CASCADE) 注释。因此,如果您使用的是 Hibernate,请尝试:

@OneToMany(targetEntity = ServiceDownload.class, cascade = { CascadeType.ALL }, fetch = FetchType.LAZY)
@OnDelete(action=OnDeleteAction.CASCADE)
private List<ServiceDownload> serviceDownloads;

有关一些示例和文档,请参阅 http://docs.jboss.org/hibernate/stable/annotations/reference/en/html/entity.html

【讨论】:

    【解决方案2】:
    • 您必须获取完整表 (FROM Product),迭代实体并使用 session.delete(..) 删除它们
    • DELETE 不会触发级联
    • 如果是原生 SQL 查询,则支持 truncate

    【讨论】:

      猜你喜欢
      • 2022-09-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-06
      • 2011-05-10
      • 1970-01-01
      • 2016-03-01
      相关资源
      最近更新 更多