簡體   English   中英

子實體中的JPA空父外鍵

[英]JPA Null parent foreign key in child entity

我無法在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。 我究竟做錯了什么?

嘗試首先實例化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);
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM