Reputation: 224
Hi i want to have a one to many relation for one of my projects, but the List is never populated.
I have a parent source class
@Entity
@Inheritance(strategy=InheritanceType.TABLE_PER_CLASS)
public class ParentJob {
@Id
@Column(name = "ID")
int id;
}
a child
@Entity
public class TakeJob extends ParentJob {
@OneToMany(fetch = FetchType.EAGER, cascade=CascadeType.REMOVE)
@JoinColumn(name="FK_JOBID", referencedColumnName="ID")
private List<JobRelation> jobRelations;
}
and a target entity
@Entity
public class JobRelation {
@EmbeddedId
private JobRelationPK JobRelationPK;
}
with a PK
@Embeddable
public class JobRelationPK implements Serializable {
private long fkSomething;
@Column(name = "FK_JOBID")
private long fkJobId;
}
Now as I said the List doesn't populate if i access it. I'm particularly interested in the syntax of the JoinColumn, since it doesn't really matter what i put for 'name' even if it's total garbage. Do i have to pay attention to what i put there or can i just put 'name = "COLUMN_NAME_IN_JOBRELATION"'
Edit: I'm using EclipseLink 2.3.2
Upvotes: 2
Views: 2044
Reputation: 21145
The problem here is probably with how you expect the JobRelation table's "FK_JOBID" field to be set.
The way you have it mapped has it writable through both the embedded JobRelationPK's fkJobId attribute AND the TakeJob's jobRelations mapping. If you are only setting it in the JobRelation entity, then the TakeJob collection will only reflect the change when it is refreshed - JPA requires that you maintain relationships so they are consistent with what is in the database. This means you still must add the JobRelation to a TakeJob's collection so that the reference is in synch with what is in the database, or refresh it after the change is commited.
But because you have two mappings to this field, the join column would need to be set to read only to avoid write problems.
A better solution might be to set up a ManyToOne relation on JobRelation to TakeJob and then set TakeJob's jobRelations mapping to be mapped by this new mapping (instead of using the joincolumn). If using JPA 2.0, you can then specify the new mapping as @MapsId("fkJobId"). something like:
@Entity public class JobRelation {
@EmbeddedId
private JobRelationPK JobRelationPK;
@ManyToOne
@MapsId("fkJobId")
private TakeJob job;
}
This will allow the embedded fkJobId attribute to be set with the value from the referenced TakeJob Id when inserted.
Upvotes: 3
Reputation: 691635
You should first be consistent on where you put your annotations in an entity hierarchy. Always put them on fields, or always put them on getters. The annotations on your getters are ignored because the @Id annotation is put on the id
field.
Once this is fixed, the name
in @JoinColumn
must be the name... of the join column. So it must be the name of the column in the JobRelation table that is a foreign key to the TakeJob table.
Upvotes: 1