在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。我做错了什么?
发布于 2016-12-05 06:56:09
尝试首先实例化Union类,然后在ServiceCharge的构造函数中初始化它。
@Test
public void Test() throws Exception {
Union u = new Union("Sindacate", 80);
UnionController.add(u);
ServiceCharge charge1 =
new ServiceCharge(60,"service for employee","27/11/2016 20:35:00", u); // uncomment your parameter here that accepts Union class type.
ServiceController.add(charge1, u);
}https://stackoverflow.com/questions/40964586
复制相似问题