[英]Not able to save data using OneToOne mapping
我正在嘗試使用OneToOne
映射將數據保存在兩個表中。我遵循了this , this , this , this和一些其他在線資源來實現此目的,但是
ORA-02291: integrity constraint (TableName.TEST_ID) violated - parent key not found
創建一個表,其中TESTID
列是外鍵。 在父表中, TESTID
是主鍵。該主鍵是使用序列生成器生成的
CREATE TABLE EW_TEST_REFTABLE (
ID int NOT NULL PRIMARY KEY,
TESTNAME VARCHAR2(20) NOT NULL,
TESTID int,
CONSTRAINT test_id FOREIGN KEY(TESTID)
REFERENCES EW_TESTDATA(TESTID)
);
Ew_testdataEntity.java(父表的實體類)
@Entity
@Table(name = "EW_TESTDATA")
public class Ew_testdata {
@Id
@SequenceGenerator(name = "sube_seq",
sequenceName = "EW_TESTDATA_SEQ",
allocationSize = 1)
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "sube_seq")
@Column(name = "TESTID")
private int testid;
@Column(name = "TESTNAME")
private String testname;
// Ew_test_reftable is another entity class.In that table the column
// TESTID (foreign key) must be same as the primary key of this
// entity/table(EW_TESTDATA)
@OneToOne(cascade = CascadeType.ALL)
@JoinColumn(name = "TESTID",unique = true)
private Ew_test_reftable ewtestreftable;
//Constructor
// getter & setter
}
Ew_test_reftable.java
@Entity
@Table(name = "EW_TEST_REFTABLE")
public class Ew_test_reftable {
@Id
@SequenceGenerator(name = "subf_seq", sequenceName = "EW_REF_SEQ", allocationSize = 1)
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "subf_seq")
@Column(name = "ID")
private int id;
@Column(name = "TESTNAME")
private String testname;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "TESTID")
private int testid;
//Constructor,getter & setter
}
使用Jpa
保存數據的服務
@Override
public Ew_testdata ew_testdata(String name) {
Ew_test_reftable ew_test_reftable = new Ew_test_reftable();
ew_test_reftable.setTestname("test");
Ew_testdata ew_testdata = new Ew_testdata();
ew_testdata.setTestname(name);
ew_testdata.setEwtestreftable(ew_test_reftable);
iew_tEst.ewTestdata(ew_testdata);
return null;
}
這個問題似乎與SO中描述的其他幾個問題類似,但我仍然無法弄清楚我在哪里犯錯
您的實體和表結構看起來相反,這使您難以理解。
現在,提到異常
ORA-02291: integrity constraint (TableName.TEST_ID) violated - parent key not found
這意味着,在向子表添加新行時,在子表中沒有父ID的引用。
在Ew_test_reftable
類中,您有
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "TESTID")
private int testid;
如果我理解正確, testid
是在你的外鍵EW_TEST_REFTABLE
,那么你為什么要使用GenerationType.IDENTITY
? 這將創建新的序列ID,並且可能與父鍵不匹配,並導致錯誤/異常。
根據我對您設計的理解,
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "TESTID")
private int testid;
改成
@OneToOne(cascade = CascadeType.ALL)
@JoinColumn(name = "TESTID",unique = true)
private Ew_testdata ew_testdata;
並且應從Ew_testdata
實體中刪除與上述代碼類似的代碼(此處可能會稍有變化)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.