JPA——在插入时使用一对一依赖关系

JPA——在插入时使用一对一依赖关系,jpa,orm,annotations,dependencies,Jpa,Orm,Annotations,Dependencies,我有两个实体类,它们的主键上有一对一的依赖关系: 主表: @Entity @Table(name = "tablePrimary") @XmlRootElement //... public class TablePrimary implements Serializable { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Basic(optional = false) @Column(name = "id") priv

我有两个实体类,它们的主键上有一对一的依赖关系:

主表:

@Entity
@Table(name = "tablePrimary")
@XmlRootElement
//...  
public class TablePrimary implements Serializable {

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Basic(optional = false)
@Column(name = "id")
private Integer id;

@Basic(optional = false)
@Column(name = "code")
private String code;

// set the dependency of table2 to this class
@OneToOne(cascade = CascadeType.ALL)  
@PrimaryKeyJoinColumn
private Table2 table2inst;  

// ...
} // end of class TablePrimary 
从属表:

@Entity
@Table(name = "table2")
@XmlRootElement
//...
public class Table2 implements Serializable {
private static final long serialVersionUID = 1L;

@Id
@Basic(optional = false)
@Column(name = "id")
private Integer id;

@Basic(optional = false)
@Column(name = "name")
private String name;

@MapsId 
@OneToOne(mappedBy = "table2inst")   
@JoinColumn(name = "id")    
private TablePrimary tablePrimaryInst;

//...

}  // end of class Table2 
每当在
TablePrimary
中有一行,比如说,
id==55
,就有 表2中id==55的行,反之亦然。 所以从本质上讲,这两个表在逻辑层是一个表——为了实用,将它们分成两个物理表

当我在“逻辑”表中插入一行时, 我首先将插入到关系中的主表
TablePrimary
, 获取我刚刚插入的新行的
id==55
字段的值,并向其插入一行 使用该id值的表2。 作为其中的一部分,我正在检查,以防万一,
id==55的行是否已在
表2中

有更好的方法吗? JPA是否具有将这两个插入到这两个物理表的功能 通过使用我在它们上配置的1-1依赖关系——而不必在代码中“手动”完成?或者我设置依赖项的表的
id
字段上的控件功能?
如果有,怎么办?它如何处理依赖表--
Table2
中的键值冲突

删除时会出现类似的情况。然而,我还不在那里,也许能从中找到答案


TIA。

您可以利用JPA级联。您必须在拥有方定义一个级联(带有联接列的级联)。如果已设置关系的拥有方并持久化拥有方,则反向方也将持久化:

TablePrimary tp = new TablePrimary();
Table2 t2 = new Table2();
t2.setTablePrimaryInst(tp);
entityManager.persist(t2);
“mappedBy”元素应该放在相反的一侧。您可以看到这样的实体:

public class Table2 ...

@OneToOne(cascade=CascadeType.ALL)  
@JoinColumn(name = "tp_id")    
private TablePrimary tablePrimary;

public class TablePrimary...

@OneToOne(mappedBy="tablePrimary")      
private Table2 table2;

我的主表的键字段是自动生成的,依赖项位于表的键字段上。当我运行插入时,我得到一个异常,即Table2的键字段不能为null。为什么不在我的代码中使用@PrimaryKeyJoinColumn呢?我听说一些JPA提供商在这个注释上有一些缺陷,是吗?