这似乎是一个很常见的情况,但作为 JPA 新手,我很难弄清楚这一点。我正在使用 EclipseLink 和 PostgreSQL,但这应该只与 JPA 规范有关。
我有一个表PRIMARY
,它有一个 ID,然后是一堆其他列。还有一个表SECONDARY
有一个外键到PRIMARY
表中,也称为ID
. 该SECONDARY
表有一个复合键ID
和一个表示语言环境的 varchar。
所以,在Primary
实体中,我想要一个类型的字段,Map<String, Secondary>
其中键是SECONDARY
表中的语言环境字符串,条目是Secondary
实体。我的Secondary
课看起来像这样:
@Entity
public class Secondary
{
@Id
private Long id;
@Id
private String locale;
private String str1;
private String str2;
.....
}
我想我想使用@MapKeyJoinColumn
注释,但我似乎无法让其他注释工作。我试过这个:
@OneToMany
@JoinColumn(name="ID")
@MapKeyJoinColumn(name="LOCALE")
private Map<String, Secondary> secondaryByLocale;
这导致它尝试选择不存在的名为 secondaryByLocale_key 的列。
然后我尝试了这个:
@OneToMany
@JoinTable(name="SECONDARY",
joinColumns={@JoinColumn(name="ID")},
inverseJoinColumns=@JoinColumn(name="ID"))
@MapKeyJoinColumn(name="LOCALE")
private Map<String, Secondary> secondaryByLocale;
这会导致以下错误:
Exception Description: The @JoinColumns on the annotated element [field secondaryByLocale] from the entity class [class com.foo.Primary] 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.
我尝试将 referencedColumnName 添加到注释中(我不确定它应该是什么),但我得到了同样的错误。
按照建议,我尝试使用@MapKey
如下:
@OneToMany
@JoinColumn(name="ID")
@MapKey(name="LOCALE")
private Map<String, Secondary> secondaryByLocale;
这会导致以下错误:
Exception Description: The map key [LOCALE] on the entity class [class com.foo.Secondary] could not be found for the mapping [org.eclipse.persistence.mappings.UnidirectionalOneToManyMapping[secondaryByLocale]].
也许我做错了,有更好的方法来注释 Map 字段。任何帮助将非常感激。