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

时间:2014-03-17 01:20:04

标签: 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")
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 

每当id==55中有一行说TablePrimary时,就会有 在id==55中具有相同Table2的行,反之亦然。 所以从本质上讲,这两个表是逻辑层面的一个表 - 为实用性分成2个物理表。

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

有更好的方法吗? JPA是否具有对这两个物理表进行这两次插入的功能 通过使用我在其上配置的1-1依赖 - 我不必在代码中“手动”执行它?或者表格的id字段上的控制功能我设置了依赖性?
如果有 - 怎么做?它如何处理从属表中的键值冲突 - Table2

删除时会出现类似的事情。但是,我还没有,可能会弄明白这一点。

TIA。

1 个答案:

答案 0 :(得分:0)

您可以利用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;