1

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 JOINs (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 e.g.

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

gene b.
  • 10,512
  • 21
  • 115
  • 227

1 Answers1

2

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.

SternK
  • 11,649
  • 22
  • 32
  • 46
  • 1
    Thanks, it actually turned out to be the opposite: in `Plans`, it should be `@JoinColumn(name="secondary_identifier", referencedColumnName = "auxiliary_identifier"`. In other words, the `@JoinColumn` is **this** table's column. Otherwise, it's working great, thank you! You might want to update the answer. – gene b. Jun 21 '20 at 21:40