【问题标题】:JPA auto-generated key not reflected in foreign key of child tableJPA 自动生成的键未反映在子表的外键中
【发布时间】:2017-02-25 20:54:07
【问题描述】:

父表:

@Table(name="parent_table_t")
public class ParentTable implements Serializable {

@Id
@Column(name="contact_id")
@GeneratedValue(strategy=GenerationType.IDENTITY)
private Integer contactId;
---------
---------
@OneToOne (cascade = CascadeType.ALL, mappedBy = "parentTable")
private ChildTable childTable;
}

子表:

@Table(name="child_table_t")
public class ChildTable implements Serializable {

@Id
@Column(name="child_id")
@GeneratedValue(strategy=GenerationType.IDENTITY)
private Integer childId;

@Column(name="contact_id")
private Integer contactId;

@JoinColumn(name="contact_id", referencedColumnName = "contact_id", insertable=false, updatable=false)
@OneToOne(cascade = CascadeType.ALL)
private ParentTable parentTable;
}

我的要求是在Parent_table_t中生成contact_id时,保存时要复制到child_table_t的contact_id中。

当我在父表实体上调用 saveAndFlush / save 时,它​​是: 为 Parent->contact_id 生成自动增量。 但是 Child_table_t -> contact_id 始终为空。 有人可以帮忙吗? 我正在使用带有 spring-boot 和 JPA 的内存 hsqldb。

【问题讨论】:

  • 您需要删除 insertable=false, updatable=false 确保设置关系的双方,即 child 中的 parentTable = 被持久化的 parent。

标签: jpa spring-boot hsqldb


【解决方案1】:

您使用 insertable=false、updatable=false 标记了关系 @JoinColumn,可能是因为您也有该列的整数映射。不幸的是,这些设置阻止 JPA 使用关系中的值设置它,而是强制使用 contactId 属性中的值设置列。

将 insertable=false, updatable=false 放在 @Column 上。

【讨论】:

  • 感谢您的帮助,但 Child_table_t -> contactId 仍然为空。
  • 是否需要初始化 parentTable / childTable 变量?
猜你喜欢
  • 2016-09-16
  • 2015-08-24
  • 2021-12-25
  • 2010-12-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-07-04
  • 2021-07-01
相关资源
最近更新 更多