One to many problem mapping when target entity has composite primary key but source not
I have a use case where a user got some profiles: So a one-to-many association.
This is mapped through these legacy tables in pseudo sql.
TABLE USER
(
ID PK
SURNAME VARCHAR2(45 BYTE) NOT NULL,
NAME VARCHAR2(45 BYTE) NOT NULL,
USER_ID NUMBER
)
TABLE USER_PROFILES
(
USER_ID NUMBER NOT NULL,
ID_PROFILO NUMBER NOT NULL,
DESCRIPTION VARCHAR2(32 BYTE)
)
This the java mapping:
@Entity
@Table(name = "USER)
public class User{
@Id
@Column(name = "ID")
private String id;
@OneToMany(fetch= FetchType.EAGER)
@JoinColumns({ @JoinColumn(name = "USER_ID", referencedColumnName = "USER_ID")})
private List<UtenteProfilo> profiles;
}
and the userprofiles class
@Entity
@Table(name = "USER_PROFILES")
@IdClass(UserProfile.UserProfileId.class)
public class UserProfile implements java.io.Serializable {
@Id
@Column(name = "USER_ID", nullable = false)
private Long userId;
@Id
@Column(name = "ID_PROFILO", nullable = false, insertable = false, updatable = false)
private Long profiloId;
private String description;
static public class UserProfileId implements Serializable {
@Id
@Column(name = "USER_ID", nullable = false)
Long userId;
@Id
@Column(name = "ID_PROFILO", nullable = false)
Long profiloId;
}
}
When I get a User from the UserDao I receive this exception:
Exception Description: The @JoinColumns on the annotated element [field profiles] from the entity class [User] is incomplete. When the source entity class uses a composite primary key, a @JoinColumn must be specified for each join column using the @JoinColumns. Both the name and the referencedColumnName elements must be specified in each such @JoinColumn.
The problem is that on the source entity (the one that gots the 1-N association) I have only one column to make the join.
I tried to change the ID on the target entity; so on the user_profiles class declaring only the user_id 开发者_运维知识库as key: but in this way when jpa creates the query it handle only one user_profiles occurence making the relation as 1-1.
Any idea how to fix the problem and make the association work?
Kind regards Massimo
JPA requires the Id be used in all relationships. You could make userId the Id in User, or use the Id as the foreign key instead of UserId.
You seem to be using EclipseLink. So you can map this as is, but you most likely need to use a DescriptorCustomizer and the API on OneToMany mapping to define the foreign key (EclipseLink support using alternative keys, just not through JPA annotations).
Technically EclipseLink should support the annotations for alternate keys, so please log a bug for this and vote for it.
精彩评论