@JoinColumn批注中名称和referencedColumnName之间的区别?

时间:2018-11-13 18:45:59

标签: java spring hibernate

@ManyToOne @JoinColumn(name =“ someValue”,referencedColumnName =“ someOtherValue”)

如果2个表被多个链接到一个关联,则应在name和referencedColumnName列中放置哪些值?

2 个答案:

答案 0 :(得分:4)

假设您有两个表:

1. Department table with columns:
 a. Dept_ID (primary key)
 b. Dept_Name

2. Employee Table with following column:
  a. Emp_Id (primary key)
  b. Dept_Id_fk (foreign key)
  c. Salary

现在您的Employee Entity类的加入列将为

@ManyToOne
@JoinColumn(name = "Dept_Id_fk", referencedColumnName = "Dept_ID")
Department department;

因此referencedColumnName表示您要从外键列引用的列。

答案 1 :(得分:1)

oneToMany 关联的连接列是什么样的?下面是一个例子:

人员表:

person_id (pk), person_name

person_reltn 表:

person_reltn_id (pk), child_person_id (fk), parent_person_id (fk)

对于上面的表格,如果我要创建 Person 实体:

 class Person(){
    
     @Id
      @Column(name = "PERSON_ID")
      private long personId;
    
      @NotFound(action = NotFoundAction.IGNORE)
      @OneToMany(fetch = FetchType.LAZY)
      @JoinColumn(
          name = "CHILD_PERSON_ID",
          referencedColumnName = "PERSON_ID",
          updatable = false,
          insertable = false)
      @Where(clause = "ACTIVE_IND = 1")
      @Filter(
          name = FilterConstants.END_EFFECTIVE_DATE_TIME_FILTER,
          condition = FilterConstants.END_EFFECTIVE_DATE_TIME_CONDITION)
      @Cache(usage = CacheConcurrencyStrategy.READ_ONLY)
      private final List<PersonRelation> personRelations = new ArrayList<>();
}

在 joinColumn 中,名称是否应该始终具有外键(这意味着您要加入的实体的值)并且 referenceColumnName 应该始终具有实体的主键?如果是,这将与上述萨彦坦的回应相反。如果我误解了这个概念,请告诉我。

03/04/2021 更新

经过更多研究,我找到了有关如何根据实体映射设置 referenceColumnName 的文档[1]。看起来,对于单向 OneToMany 映射,引用的列在源实体的表中。

1.https://docs.jboss.org/hibernate/jpa/2.1/api/javax/persistence/JoinColumn.html