gpt4 book ai didi

hibernate - 使用 JPA @MapsId 注释共享主键

转载 作者:行者123 更新时间:2023-12-03 18:38:55 27 4
gpt4 key购买 nike

为了共享 1<>1 关系的主键,我尝试使用 JPA @MapsId 注释但我没有成功。

这是我的 sql 表生成:

CREATE TABLE `myschema`.`table2` (
`id` INT NOT NULL AUTO_INCREMENT,
`coltable2` VARCHAR(45) NULL,
PRIMARY KEY (`id`));

CREATE TABLE `myschema`.`table1` (
`id` INT NOT NULL,
`coltable1` VARCHAR(45) NULL,
PRIMARY KEY (`id`),
CONSTRAINT `fk`
FOREIGN KEY (`id`)
REFERENCES `myschema`.`table2` (`id`)
ON DELETE CASCADE
ON UPDATE CASCADE);

这是我的两个类:

表格1:
@Entity
@Table(name="table1")
public class Table1 {

@Id
private int id;

@OneToOne(cascade=CascadeType.ALL, fetch = FetchType.EAGER)
@JoinColumn(name="id")
@MapsId(value="id")
private Table2 table2;

....

}

表 2:
@Entity
@Table(name="table2")
public class Table2 {

@Id @GeneratedValue
private int id;

@OneToOne(cascade=CascadeType.ALL, fetch = FetchType.EAGER, mappedBy = "table2")
private Table1 table1;

...

}

因此,当尝试通过这样做来保存时:
Table1 table1 = new Table1();
table1.setColTable1("table1");

Table2 table2 = new Table2();
table2.setColTable2("table2");

table1.setTable2(table2);
table2.setTable1(table1);

dao.save(table1);

我收到以下错误:

com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException: Cannot add or update a child row: a foreign key constraint fails



似乎@MapsId 没有将 id 值从 table2 标识符传播到 table1 标识符。所以约束不受尊重。但我不明白代码有什么问题?

有人可以指出我的错误吗?

最佳答案

我不确定 @MapsId是你想要的。
@PrimaryKeyJoinColumn可能是你需要的:

and it may be used in a OneToOne mapping in which the primary key of the referencing entity is used as a foreign key to the referenced entity.



http://docs.oracle.com/javaee/5/api/javax/persistence/PrimaryKeyJoinColumn.html

http://vard-lokkur.blogspot.co.uk/2011/05/onetoone-with-shared-primary-key.html

关于hibernate - 使用 JPA @MapsId 注释共享主键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20070535/

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