gpt4 book ai didi

java - 无法使用 OneToOne 映射保存数据

转载 作者:行者123 更新时间:2023-11-29 10:25:25 29 4
gpt4 key购买 nike

我正在尝试使用 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 类(class)中,您有

@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 实体中删除(这里和那里可能会有轻微的变化)

关于java - 无法使用 OneToOne 映射保存数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48393822/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com