【问题标题】:Hibernate: Can I use mappedBY Annotation without using @joincolumn [closed]Hibernate:我可以在不使用 @joincolumn 的情况下使用 mappedBY Annotation [关闭]
【发布时间】:2020-04-29 23:56:49
【问题描述】:

我有两个表,我需要在它们之间建立关系。有一个要求:不要使用@joinColumn注解,那我可以用MappedBy实现吗?关系可以是任何类型,例如 OneToOneManyToOneManyToMany

【问题讨论】:

    标签: java hibernate orm mapping relation


    【解决方案1】:

    要实现双向映射时需要加入列。 如果您想要单向行为,则不需要 @JoinColumn。

    参考:https://vladmihalcea.com/the-best-way-to-map-a-onetomany-association-with-jpa-and-hibernate/

    @ManyToMany 映射不应该是这种情况,因为它需要一个单独的 JoinTable 来维护这种关系。

    【讨论】:

      【解决方案2】:

      可能有人会纠正我,但据我所知,JPAHibernate 中都没有 @mappedBy 注释。关系注释@OneToMany等只有一个参数mappedBy。 此外,使用此参数意味着您已经在所有者方面具有单向关系,并且只允许您通过定义此属性来创建双向关联。 所以通常你不能在拥有方使用没有@JoinColumn 注释的mappedBy 参数。假设您有一个实体:

      @Entity
      public class Document {
      
          @Id
          @GeneratedValue(strategy = GenerationType.AUTO)
          private Long id;
      
          @ManyToOne(fetch = FetchType.LAZY)
          @JoinColumn(name = "person_id")
          private Person person;
      
          // ...
      
      }
      

      那么mappedBy 的用法将是:

      @Entity
      public class Person {
      
          @Id
          @GeneratedValue(strategy = GenerationType.AUTO)
          private Long id;
      
          @OneToMany(fetch = FetchType.LAZY, mappedBy = "person")
          private List<Document> documents;
      
          // ...
      }
      

      更多信息见Hibernate reference

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2016-01-15
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-12-17
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多