【发布时间】:2016-12-04 22:41:33
【问题描述】:
我无法将子外键设置为 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 添加到服务费列表中,然后将实体持久化到数据库。
但是,测试正常,但我只能看到这个:
| 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。我做错了什么?
【问题讨论】:
标签: java mysql entity-framework hibernate jpa