简体   繁体   English

如何通过 Hibernate 中具有不同名称的非 PK 列 map 2 个表

[英]How to map 2 tables through non-PK columns with different names in Hibernate

I have 2 tables that may be related to each other through non-PK secondary columns.我有 2 个表,它们可能通过非 PK 辅助列相互关联。 Moreover, the column names for this match are different in each table.此外,此匹配的列名在每个表中都不同。 That is,那是,

@Entity
@Table(name = "PLANS_T")
public class Plans {
    private Integer id; // PK
    //...
    private String secondaryIdentifier; // Should be matched with TRAINEES.auxiliaryIdentifier
    //...
}

@Entity
@Table(name = "TRAINEES_T")
public class Trainee {    
    private Integer id; // PK
    //...
    private String auxiliaryIdentifier; // Should be matched with PLANS.secondaryIdentifier
}

The relationship between PLANS and TRAINEE is Many-to-One: You can have many Plans for a Trainee. PLANSTRAINEE之间的关系是多对一的:您可以为受训者制定多个计划。

I need to annotate these properly to indicate that PLANS_T.secondaryIdentifier should be used with TRAINEES_T.auxiliaryIdentifier for JOIN s (such as in the Criteria API, which needs a Join Path from one table to the other).我需要正确注释这些以指示PLANS_T.secondaryIdentifier应与TRAINEES_T.auxiliaryIdentifier一起用于JOIN (例如在标准 API 中,它需要从一个表到另一个表的连接路径)。

But I can't use the typical examples eg但我不能使用典型的例子,例如

@Entity
class Trainee {

    @OneToMany(mappedBy = "plan")
    private Collection<Plans> plans = new ArrayList<Plans>();

}

@Entity
class Plans {

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name="auxiliary_identifier") // Where do I specify "secondaryIdentifier", a non-PK column?
    private Trainee trainee;

}

I need a way to specify both of the non-PK columns in the annotations.我需要一种方法来指定注释中的两个非 PK 列。 When using Criteria API, these annotations provide the path to create Join paths.使用 Criteria API 时,这些注释提供了创建 Join 路径的路径。

You should correct your mapping in the following way:您应该通过以下方式更正您的映射:

@Entity
class Trainee {

   @OneToMany(mappedBy = "trainee")
   private List<Plans> plans = new ArrayList<Plans>();
}

@Entity
class Plans {

   @ManyToOne(fetch = FetchType.LAZY)
   @JoinColumn(name="secondary_identifier", referencedColumnName = "auxiliary_identifier")
   private Trainee trainee;

}
  1. The mappedBy of the @OneToMany is the name of the field that owns the relationship. @OneToManymappedBy是拥有关系的字段的名称。 This is trainee field of the Plans entity.这是Plans实体的trainee字段。

  2. The referencedColumnName of the @JoinColumn is the name of the column referenced by this foreign key column. @JoinColumnreferencedColumnName是该外键列引用的列的名称。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM