删除关联的一部分时,Hibernate从关联表中删除条目

时间:2014-03-18 17:54:21

标签: java hibernate jpa many-to-many

我有以下hibernate映射:

班级杂志:

@Entity
@Table(name = "PROJECTNAME_MAGAZINE")
@SequenceGenerator(name = "MAGAZINE_SEQUENCE_GENERATOR", sequenceName = "MAGAZINE_SEQUENCE")
@Analyzer(definition = "customanalyzer")
public class Magazine extends AbstractBaseEntity implements Serializable{


@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "MAGAZINE_SEQUENCE_GENERATOR")
@Column(name = "ID")
private Long id;
@NotNull
@Field(index=Index.YES, analyze=Analyze.YES, store=Store.NO)

@LazyCollection(LazyCollectionOption.FALSE)
@OneToMany(cascade = CascadeType.ALL, mappedBy="magazine", orphanRemoval = true)
private List<MagazineKeywordMapper> magazineKeywordMappings;

Class MagazineKeyword

@Entity
@Table(name = "PROJECTNAME_MAGAZINE_KEYWORD")
public class MagazineKeyword extends AbstractBaseEntity {

public MagazineKeyword(String keyword) {
    this.keyword = keyword;
    this.id = (long) keyword.hashCode();
}

@Id
@Column(name = "ID")
private Long id;

@OneToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER, mappedBy="keyword",orphanRemoval=true)
private List<MagazineKeywordMapper> magazineMappings;

Class MagazineKeywordMapper

@Entity
@Table(name="MAGAZINE_KEYWORD_MAPPER")
public class MagazineKeywordMapper extends AbstractBaseEntity implements Serializable  {

private static final long serialVersionUID = 1L;

@Id
@Column(name = "ID")
private Long id;

@ManyToOne
    @PrimaryKeyJoinColumn(name="MAGAZINE_ID", referencedColumnName="ID")
    private Magazine magazine;


    @ManyToOne
    @PrimaryKeyJoinColumn(name="KEYWORD_ID", referencedColumnName="ID")
    private MagazineKeyword keyword;

    public MagazineKeywordMapper() {

    }

public MagazineKeywordMapper(Magazine magazine, MagazineKeyword keyword) {
    this.magazine = magazine;
    this.keyword = keyword;
    this.id = Long.parseLong(magazine.getId()+""+keyword.getId());
}

我尝试了很多东西,但不知怎的,我无法找到一种在映射上删除的好方法。如果删除关键字,我希望删除包含此关键字的所有映射。不知怎的,我得到的是IntegrityConstraintViolations ......我做错了什么?我使用DAO并在关键字对象上调用EntityManager.remove()。我还尝试从相关的Magazine对象中手动删除映射。任何提示都非常感谢。谢谢你的帮助!:)

3 个答案:

答案 0 :(得分:0)

因为我看到你没有使用懒惰的提取类型。它会解决你的问题。使用类似的解决方案:

@OneToMany(fetch = FetchType.LAZY, cascade = CascadeType.ALL, mappedBy = "xxx")

答案 1 :(得分:0)

级联策略是您需要查看的内容

Hibernate Documentation

Stackoverflow thread

答案 2 :(得分:0)

发现问题:我对限制删除的数据库有约束。将它设置为级联,现在一切都运行良好!