hibernate一对多更新跳过uniqueConstraints检查

时间:2013-12-26 15:15:23

标签: java hibernate jpa

我正在开展一个项目,我需要使用关键字保存下载文件信息。 典型的一对多场景,对吗?许多下载关键字关系记录的下载记录。

所以这是Download.java的样子

    @Entity
@Table(name = "downloads", catalog = "nbpx")
public class Download extends BaseEntity implements Serializable {
public Integer downloadId;
public String title;
public Set<DownloadKeyword> downloadKeywords = new HashSet<DownloadKeyword>(
        0);
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "downloadId", unique = true, nullable = false)
public Integer getDownloadId() {
    return downloadId;
}


public void setDownloadId(Integer downloadId) {
    this.downloadId = downloadId;
}


public String getTitle() {
    return title;
}


public void setTitle(String title) {
    this.title = title;
}

    @OneToMany(fetch = FetchType.EAGER, mappedBy = "download")
@Cascade({CascadeType.SAVE_UPDATE, CascadeType.DELETE})
public Set<DownloadKeyword> getDownloadKeywords() {
    return downloadKeywords;
}

public void setDownloadKeywords(Set<DownloadKeyword> downloadKeywords) {
    this.downloadKeywords = downloadKeywords;
}
    }

由于我不希望表中有任何重复的下载关键字关系记录,因此我为该类设置了JPA唯一约束。但我没有使用复合键。这就是DownloadKeyword.java的样子:

@Entity
@Table(name = "downloadkeywords", catalog = "nbpx", uniqueConstraints =
       @UniqueConstraint(columnNames = {"keywordId", "downloadId" }))
public class DownloadKeyword extends BaseEntity implements Serializable {
private static final long serialVersionUID = 1L;
public Integer downloadKeywordId;
public Download download;
public Integer keywordId;
    @Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "downloadKeywordId", unique = true, nullable = false)
public Integer getDownloadKeywordId() {
    return downloadKeywordId;
}

public void setDownloadKeywordId(Integer downloadKeywordId) {
    this.downloadKeywordId = downloadKeywordId;
}

@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "downloadId", nullable = false, insertable=true)
public Download getDownload() {
    return download;
}

public void setDownload(Download download) {
    this.download = download;
}

public Integer getKeywordId() {
    return keywordId;
}

public void setKeywordId(Integer keywordId) {
    this.keywordId = keywordId;
}
}

当我保存下载实体时,我希望看到所有下载关键字关系实体都保存在下载实体保存会话中。我需要避免下载关键字关系表中的重复。但每次我保存它时,关系记录直接插入到DB中,而不检查与JPA注释的重复。

所以这是我的问题:当实体在一对多保存或更新会话中保存时,是否会忽略JPA注释的多列uniqueConstraints?

1 个答案:

答案 0 :(得分:1)

uniqueConstraints 仅适用于表格生成支持。 请参阅documentation

由于您已在下载类中使用Set<DownloadKeyword>,因此您可以在中实现 hashCode 等于方法strong> DownloadKeyword 类(包括主键 downloadKeywordId keywordId 属性)以实现您的目标。

但是,我仍然更喜欢复合键方法。