主键为外键的一对一映射-需要哪些注释 [英] One-to-one mapping where primary key is foreign key - what annotations are required

查看:95
本文介绍了主键为外键的一对一映射-需要哪些注释的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有下表:

Table: MyEntity {
    MyEntityId: primary-key, auto-generated
    // other fields ommited
}

Table: MyEntityLastAction {
    MyEntityId: primary-key
    // other fields ommited
}

  • MyEntityLastAction.MyEntityId有一个约束,它必须存在于MyEntity中. (这是一个外键)
  • MyEntityLastAction是一个非常大的记录,因此为什么将它拆分到另一个表中
    • MyEntityLastAction.MyEntityId has a constraint that it must exist in MyEntity. (This is a foreign key)
    • MyEntityLastAction is a VERY BIG record, hence why it is split out into another table
    • 我无法正确设置实体注释.这大概是我的位置:

      I am failing to setup the entity annotations correctly. Here is roughly where I am:

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

      推荐答案

      我认为您正在寻找@MapsId批注.这样可以使@OneToOne具有共享的主键.

      I think you are looking for @MapsId annotation. This allows you to have @OneToOne with shared primary key.

      请参见以下代码以供参考:

      See the below code for reference:

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

      这篇关于主键为外键的一对一映射-需要哪些注释的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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