简体   繁体   中英

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. 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.

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

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. When using Criteria API, these annotations provide the path to create Join paths.

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. This is trainee field of the Plans entity.

  2. The referencedColumnName of the @JoinColumn is the name of the column referenced by this foreign key column.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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