主键是外键的一对一映射 - 需要注释的内容

时间:2016-03-08 16:43:45

标签: java jpa

我有以下表格:

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);

1 个答案:

答案 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);