开发者

Master/Detail relationship with auto increment. Is it possible to persist them at once?

I have this scenario :

tbl_master(
  master_field_pk int(11) NOT NULL AUTO_INCREMENT,
  PRIMARY KEY (`master_field_pk`)
)

and

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`)
)

This is my hibernate class for master :

@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
}

and this one is for detail :

@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
}

To insert, i use this block of code (more or less) :

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();

All the records (the master record and the details record) are perfectly inserted. However, the master_field_pk in tbl_detail - the foreign key - is still null. Is it possible to avoid this behavior? Thanks


No. You have to persist the master first. The detail rows need to know what the master ID is to be linked.

This can be done but only when the key is assigned by the application, for example GUID keys assigned by the application, or some sort of key server.


CascadeType.ALL should do the trick for you. It has worked for me all the time.

I think your problem lies in your @GeneratedValue attribute strategy. You should be using GenerationType.IDENTITY instead of GenerationType.AUTO.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜