Reputation: 11994
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 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.
Upvotes: 1
Views: 384
Reputation: 13051
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;
}
The mappedBy
of the @OneToMany
is the name of the field that owns the relationship. This is trainee
field of the Plans
entity.
The referencedColumnName
of the @JoinColumn
is the name of the column referenced by this foreign key column.
Upvotes: 2