[英]One to One unidirectional mapping with same primary key in hibernate
I have two classes/tables (Metafile and RowCount) with a one to one relation. 我有两个具有一对一关系的类/表(Metafile和RowCount)。 Rowcount only applys to certain metafiles. 行数仅适用于某些图元文件。 Currently I have this set up (simplified): 目前,我已经进行了此设置(简化):
@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...
}
I'm using crudrepositories for both to simplify persistance. 我都使用crudrepository来简化持久性。
I first save the metafile to get an ID assigned, then I create a rowcount object using that metafile with the new ID and save it (shown below). 我首先保存图元文件以获取分配的ID,然后使用具有新ID的图元文件创建一个行计数对象,然后保存它(如下所示)。 This second save fails however, as the metafile isn't persisted to the database immediately, and the foreign key constraint fails. 但是,第二次保存失败,因为图元文件不会立即持久保存到数据库中,并且外键约束也失败了。
metaFile = fileRepository.save(metaFile);
rowCountRepository.save(new RowCount(metaFile,getNumberOfRows(file));
The metaFile definitely gets a valid id assigned to it. metaFile肯定会获得分配给它的有效ID。 Is there a way to make sure these two persists happen in order? 有没有办法确保这两个持久性顺序发生?
Thanks! 谢谢!
You can change your mapping with @mapsId
as suggested by Hadi J to have a single pk/fk column in RowCount
你可以改变你的映射@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...
}
I would use a bidirectional relationship to simplify saving: 我将使用双向关系来简化保存:
@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;
}
This way you can just set the relationship and save 这样您就可以设置关系并保存
RowCount rowCount = new RowCount(metaFile, getNumberOfRows(file));
metaFile.setRowCount(rowCount);
metaFile = fileRepository.save(metaFile);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.