【问题标题】:One to One unidirectional mapping with same primary key in hibernate休眠中具有相同主键的一对一单向映射
【发布时间】:2018-04-19 12:33:13
【问题描述】:

我有两个具有一对一关系的类/表(元文件和行计数)。行数仅适用于某些元文件。目前我有这个设置(简化):

元文件.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 的元文件创建行计数对象并保存(如下所示)。然而,第二次保存失败,因为元文件没有立即保存到数据库中,并且外键约束失败。

metaFile = fileRepository.save(metaFile);

rowCountRepository.save(new RowCount(metaFile,getNumberOfRows(file));

metaFile 肯定会获得分配给它的有效 id。有没有办法确保这两个持续发生?

谢谢!

【问题讨论】:

  • 你用'PRIMARYJOINCOLUMN'或者@mapsId注解测试了吗?
  • @HadiJ 将主键连接列添加到 MetaFile 中的新 RowCount 字段,并将带有 JoinColumn 的 MapsId 添加到 RowCount。但是,在保存时,我现在得到一个空标识符。

标签: java hibernate spring-boot spring-data-jpa one-to-one


【解决方案1】:

您可以按照 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);

【讨论】:

  • 爱它!它也几乎可以工作。我正在使用带有休眠的现有模式,并且在模式验证期间我收到错误“表 [row_count] 中缺少列 [file_file_id]”。目前正在研究为什么将 file_ 附加到开头。
  • 我将 @JoinColumn(name = "file_id") 添加到 RowCount 的 File 字段中,然后将其移至。
猜你喜欢
  • 2013-05-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-06-22
  • 1970-01-01
  • 1970-01-01
  • 2014-08-20
相关资源
最近更新 更多