使用Hibernate注释的一个表到多表映射

时间:2013-07-31 09:49:16

标签: hibernate session struts2 annotations mapping

就我而言:

Rack和Slot是具有自定义ID生成器的实体。我正在使用单向一对一映射。维度表将使用自动生成的自定义ID作为多个表的外键来保存数据(例如,此处为机架和插槽)。我的架构如下所示:Rack ------> Dimension< ----------- Slot,其中Dimension将保存带有生成ID的Rack和Slot表的数据。

这里的问题是,当我保存这样的数据时: -

Rack rack = new Rack(params);
Dimension dim = new Dimension(params);
rack.setDimension(dim);
session.save(rack);

使用相同的自动生成ID在Rack和Dimension Tables中成功保存数据。

但是当我保存Slot表的数据时:

Slot Slot = new Slot(params);
Dimension dim = new Dimension(params);
slot.setDimension(dim);
session.save(slot);

它显示错误消息: -

尝试从null一对一属性中分配id:rack

我可以在保存Slot and Dimension的数据时将动态属性名称作为“slot”传递,并在保存Rack和Dimension的数据时将其“传送”。

Rack.java

@Entity
@Table(name="tablename")
@GenericGenerator(name = "customseq", strategy = "CustomIdGenerator")
public class Rack {
  @Id
  @GeneratedValue(generator = "customseq")
  @Column(name = "uni_id")
  private String id;
  @OneToOne(fetch = FetchType.LAZY, cascade = CascadeType.ALL)
  @PrimaryKeyJoinColumn
  private Dimension dimension;
  // Getters and Setters
}

Slot.java

@Entity
@GenericGenerator(name = "slot_seq", strategy = "com.slot.SlotIdGenerator")
@Table(name = "\"slot_info\"")
public class Slot implements Serializable {

  @Id
  @GeneratedValue(generator = "slot_seq")
  @Column(name = "slot_id")
  private String slotid;
  @Column(name = "rack_id")
  private String rackid;
  @Column(name = "element_id")
  private String elementid;
  @Column(name = "sr_no")
  private int srno;   
  @JoinColumn(name = "systemid", insertable = false, updatable = false)
  @PrimaryKeyJoinColumn
  private Dimension dimension;
  // getters and setters
}

Dimension.java

public class Dimension implements Serializable{
  @Id
  @Column(name = "systemid")
  @GeneratedValue(generator = "foreign")
  @GenericGenerator(name = "foreign", strategy = "foreign", parameters = {
  @Parameter(name = "property", value = "slot"),
  @Parameter(name = "property", value = "rack")})
  private String systemid;

  @OneToOne(mappedBy = "dimension", fetch = FetchType.LAZY)
  @PrimaryKeyJoinColumn
  private Rack rack;
  @OneToOne(mappedBy = "dimension", fetch = FetchType.LAZY)
  @PrimaryKeyJoinColumn
  private Slot slot;
  // Getters and Setters
}

0 个答案:

没有答案