[英]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.