具有JPA @MapsId批注的共享主键 [英] Shared primary key with JPA @MapsId annotation

查看:201
本文介绍了具有JPA @MapsId批注的共享主键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

要共享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);

我收到以下错误:

com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException:无法添加或更新子行:外键约束失败

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

@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可能是您需要的:

,它可用于OneToOne映射中,其中的主键为 引用实体用作所引用对象的外键 实体.

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

这篇关于具有JPA @MapsId批注的共享主键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆