我有以下表格:
Table: MyEntity {
MyEntityId: primary-key, auto-generated
// other fields ommited
}
Table: MyEntityLastAction {
MyEntityId: primary-key
// other fields ommited
}
MyEntityLastAction.MyEntityId
有一个约束条件,它必须存在于MyEntity
中。 (这是外键)MyEntityLastAction
是一个非常大的记录,因此它被分成另一个表我无法正确设置实体注释。这大致是我的位置:
@Entity
public class MyEntity {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
public long myEntityId;
@OneToOne(fetch = FetchType.LAZY, cascade = CascadeType.ALL, orphanRemoval = true)
public MyEntityLastAction lastAction;
}
@Entity
public class MyEntityLastAction {
@Id
public long myEntityId;
@OneToOne(mappedBy = "MyEntity", fetch = FetchType.LAZY, cascade = CascadeType.ALL, orphanRemoval = true)
@JoinColumn(name = "MyEntityId")
public MyEntity myEntity;
}
我想尝试运行以下内容:
MyEntity myEntity = new MyEntity();
myEntity.lastAction = new MyEntityLastAction();
em.save(myEntity);
答案 0 :(得分:1)
我认为您正在寻找@MapsId
注释。这允许您使用共享主键@OneToOne
。
请参阅以下代码以供参考:
@Entity
class MyEntity {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
public long myEntityId;
@OneToOne(mappedBy = "myEntity", fetch = FetchType.LAZY, cascade = CascadeType.ALL, orphanRemoval = true)
public MyEntityLastAction lastAction;
}
@Entity
class MyEntityLastAction {
@Id
public long myEntityId;
@OneToOne
@JoinColumn(name="MyEntityId")
@MapsId
public MyEntity myEntity;
}
并保存实体:
MyEntity me = new MyEntity();
me.lastAction = new MyEntityLastAction();
me.lastAction.myEntity = me;
entityManager.persist(me);