![](/img/trans.png)
[英]JPA / Hibernate unidirectional one-to-one mapping with shared primary key
[英]One to One unidirectional mapping with same primary key in hibernate
我有兩個具有一對一關系的類/表(Metafile和RowCount)。 行數僅適用於某些圖元文件。 目前,我已經進行了此設置(簡化):
@Entity
@Table(name = "file")
public class MetaFile {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "file_id")
private int fileId;
// getters, setters, constructors...
}
@Entity
@Table(name = "row_count")
public class RowCount implements Serializable {
@OneToOne
@JoinColumn(name="file_id")
private MetaFile file;
@Id
@Column(name="file_id")
private int file_id; // duplicate field needed so that crudrepo would recognise the id
private int rows;
public RowCount(MetaFile file, int rows) {
this.file = file;
this.rows = rows;
this.file_id = file.getFileId();
}
// getters, setters...
}
我都使用crudrepository來簡化持久性。
我首先保存圖元文件以獲取分配的ID,然后使用具有新ID的圖元文件創建一個行計數對象,然后保存它(如下所示)。 但是,第二次保存失敗,因為圖元文件不會立即持久保存到數據庫中,並且外鍵約束也失敗了。
metaFile = fileRepository.save(metaFile);
rowCountRepository.save(new RowCount(metaFile,getNumberOfRows(file));
metaFile肯定會獲得分配給它的有效ID。 有沒有辦法確保這兩個持久性順序發生?
謝謝!
你可以改變你的映射@mapsId
由哈迪J所示有一個單人PK / FK列RowCount
@Entity
@Table(name = "row_count")
public class RowCount implements Serializable {
@OneToOne
@JoinColumn(name = "file_id")
@MapsId
private MetaFile file;
@Id
@Column(name="file_id")
private int file_id;
private int rows;
public RowCount(MetaFile file, int rows) {
this.file = file;
this.rows = rows;
}
// getters, setters...
}
我將使用雙向關系來簡化保存:
@Entity
@Table(name = "file")
public class MetaFile {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "file_id")
private int fileId;
// getters, setters, constructors...
@OneToOne(cascade = {CascadeType.ALL}, mappedBy = "file")
private RowCount rowCount;
}
這樣您就可以設置關系並保存
RowCount rowCount = new RowCount(metaFile, getNumberOfRows(file));
metaFile.setRowCount(rowCount);
metaFile = fileRepository.save(metaFile);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.