0
我无法在OneToMany双向关系中将子外键设置为父项。我有一个父类联盟的定义是这样的:JPA在子实体中为空的父外键
@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列表中,然后persis将实体放入数据库中。
然而,测试去正确的,但我只能看到这一点:
| 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。我究竟做错了什么?
你救了我。事实上,从概念上来说这是对的,因为没有与之相关的联盟就无法存在服务代码。但是现在,我与Employee关系有着同样的问题,但现在我不应该将Union调用到构造函数中,因为现在它甚至可以为null,并且我不喜欢每次都将null作为参数传递的想法。 – Andrew
那么到目前为止的输出是什么?我认为你可以重载你的构造函数,以便你可以选择你应该使用的构造函数。所以你可以有选择。具有联合参数和不具有联合参数的构造函数的构造函数。 – msagala25
我不能这样做,因为员工可以在实例化之后再决定与工会关联。允许空值。 – Andrew