我无法将子外键设置为OneToMany双向关系中的父外键。我有这样定义的父类Union:
@Entity
@PrimaryKeyJoinColumn(referencedColumnName="id")
@Table(name="union_tb")
@Inheritance( strategy = InheritanceType.JOINED )
public class Union extends User{
@Column(unique=true)
String Name;
float uniondue = 0;
@OneToMany(targetEntity=ServiceCharge.class,cascade=CascadeType.REMOVE, orphanRemoval=true,fetch = FetchType.EAGER,mappedBy="union")
List<ServiceCharge> ServiceCharges;
@OneToMany(targetEntity=Employee.class,cascade=CascadeType.REMOVE, orphanRemoval=true,fetch = FetchType.EAGER)
List<Employee> Employee;
public void PostServiceCharge(ServiceCharge charge) {
ServiceCharges.add(charge);
}
子类ServiceCharge以这种方式定义:
@Entity
@Table
public class ServiceCharge implements Serializable{
@Id @GeneratedValue(strategy= GenerationType.AUTO)
int ChargeID;
String Service;
@Temporal(TemporalType.TIMESTAMP)
Calendar TimeStamp;
float ChargeAmount;
@ManyToOne
@JoinColumn(name="union_id")
Union union;
public ServiceCharge(){super();}
public ServiceCharge(float chargeAmount, String service, String timestamp/*, Union union*/) throws ParseException {
super();
ChargeAmount = chargeAmount;
Service = service;
TimeStamp = TimeManagUtil.getGCobjectfromString(timestamp);
//this.Union = union;
}
// getters and setters
}
然后我运行测试代码:
@Test
public void Test() throws Exception {
ServiceCharge charge1 = new ServiceCharge(60,"service for employee","27/11/2016 20:35:00");
Union u = new Union("Sindacate", 80);
UnionController.add(u);
ServiceController.add(charge1, u);
}
正如你所看到的,我在将Union u保存到数据库之后与控制器关联这两个实体,ServiceController.add只是通过使用Union setter将实体charge1添加到servicecharges列表中,然后将实体持久化数据库。
然而,测试正确,但我只能看到:
| ChargeID | ChargeAmount | Service | TimeStamp | union_id |
+----------+--------------+----------------------+---------------------+----------+
| 6 | 60 | service for employee | 2016-11-27 20:35:00 | NULL |
| 7 | 10 | service for employee | 2016-11-27 20:45:00 | NULL
| Name | uniondue | id |
+-----------+----------+----+
| Sindacate | 80 | 5 |
+-----------+----------+----+
如您所见,union_id设置为null。我做错了什么?