我有两个具有一对一关系的类/表(元文件和行计数)。行计数仅适用于某些图元文件。目前我已经这样设置(简化):
元文件.java
@Entity
@Table(name = "file")
public class MetaFile {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "file_id")
private int fileId;
// getters, setters, constructors...
}
RowCount.java
@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...
}
我使用 crudrepositories 来简化持久性。
我首先保存图元文件以获取分配的 ID,然后使用该图元文件和新 ID 创建一个 rowcount 对象并保存它(如下所示)。然而,第二次保存失败,因为图元文件没有立即保存到数据库,并且外键约束失败。
metaFile = fileRepository.save(metaFile);
rowCountRepository.save(new RowCount(metaFile,getNumberOfRows(file));
metaFile 肯定会获得分配给它的有效 ID。有没有办法确保这两个持续按顺序发生?
谢谢!
最佳答案
您可以按照 Hadi J 的建议,使用 @mapsId
更改映射,以便在 RowCount
中拥有单个 pk/fk 列
@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);
关于java - hibernate中具有相同主键的一对一单向映射,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49921243/