问题描述
要共享1<> 1关系的主键,我试图使用JPA @MapsId批注,但未成功.
To have shared primary key for a 1<>1 relationship, I'm trying to use JPA @MapsId annotation but I didn't succeed.
这是我的sql表生成:
Here is my sql table generation :
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;
...
}
因此,当您尝试通过以下操作进行保存时:
So when trying to save by doing this:
Table1 table1 = new Table1();
table1.setColTable1("table1");
Table2 table2 = new Table2();
table2.setColTable2("table2");
table1.setTable2(table2);
table2.setTable1(table1);
dao.save(table1);
我收到以下错误:
@MapsId似乎没有将id值从table2标识符传播到table1标识符.因此不遵守约束.但是我看不出代码有什么问题吗?
It seems like @MapsId did not propagate id value from table2 identifier to table1 identifier. So the constraint is not respected. But I don't see what's wrong with the code?
请问有人指出我的错误吗?
Could someone point out my error, please?
推荐答案
我不确定@MapsId
是否就是您想要的.
I'm not sure that @MapsId
is what you want here.
@PrimaryKeyJoinColumn
可能是您需要的:
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
这篇关于具有JPA @MapsId批注的共享主键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!