我有这样一个场景:
tbl_master(
master_field_pk int(11) NOT NULL AUTO_INCREMENT,
PRIMARY KEY (`master_field_pk`)
)
和
tbl_detail(
`detail_field_pk` int(11) NOT NULL AUTO_INCREMENT,
`master_field_pk` int(11) DEFAULT NULL,
CONSTRAINT `child_fk1` FOREIGN KEY (`master_field_pk`) REFERENCES `tbl_master` (`master_field_pk`) ON DELETE NO ACTION ON UPDATE NO ACTION,
PRIMARY KEY (`master_field_pk`)
)
这是我的冬眠大师班:
@Entity
@Table(name = "tbl_master")
@Name("TblMaster")
public class TblMaster implements Serializable{
@Id
@Column(name = "master_field_pk")
@GeneratedValue(strategy = GenerationType.AUTO)
private Integer MasterFieldPk;
@Cascade({CascadeType.ALL,CascadeType.DELETE_ORPHAN})
@OneToMany(mappedBy="tblMaster")
@JoinColumn(name="master_field_pk", insertable=true, updatable=true, referencedColumnName="master_field_pk")
private Set<TblDetail> tblDetails;
@Transient
private List<TblDetail> tblDetailsList;
// any other things
}
这个是为了细节:
@Entity
@Table(name="tbl_detail")
@Name("TblDetail")
public class TblDetail implements Serializable{
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
@Column(name="detail_field_pk")
private Integer detailFieldPk;
@Column(name="master_field_pk")
private Integer MasterFieldPk;
@ManyToOne(fetch=FetchType.LAZY)
@JoinColumn(name="master_field_pk", insertable = false, updatable = false, referencedColumnName = "master_field_pk")
private TblMaster tblMaster;
// any other things
}
要插入,我使用此代码块(或多或少):
TblDetail detail_1 = ...
detail_1.setTblMaster(tblMaster);
// and so on ..
Set<TblDetails> set = ...
set.add(detail_1);
// and so on...
tblMaster.setTblDetails(set);
em.persist(tblMaster);
em.flush();
所有记录(主记录和详细记录)都已完全插入。但是,
master_field_pk
中的tbl_detail
外键-仍然为空。有可能避免这种行为吗?谢谢 最佳答案
不,你必须先坚持主人。细节行需要知道要链接的主ID。
只有当应用程序分配了密钥(例如,应用程序分配的GUID密钥)或某种密钥服务器时,才能执行此操作。