[英]JPA - @OneToMany as a Map
这似乎是一个常见的案例,但作为JPA新手,我很难搞清楚这一点。 我正在使用EclipseLink和PostgreSQL,但这应该只涉及JPA规范。
我有一个表PRIMARY
有一个ID,然后是一堆其他列。 还有另一个表SECONDARY
,它在PRIMARY
表中有一个外键,也称为ID
。 此SECONDARY
表具有该ID
的复合键和表示语言环境的varchar。
因此,在Primary
实体中,我想要一个Map<String, Secondary>
类型的字段,其中key是来自SECONDARY
表的locale字符串,该条目是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字段。 任何帮助将非常感激。
请尝试使用@MapKey(name = "locale")
。
当您的地图关键字是实体时使用@MapKeyJoinColumn
,但在这里您只使用区域设置字符串。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.