我正在尝试使用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中描述的其他几个问题类似,但我仍然无法弄清楚我在哪里犯错误
答案 0 :(得分:1)
你的实体和表格结构看起来相反,这让人很难理解。
现在,提到例外
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
实体中删除(此处可能会略有变化)