dnc*_*253 15 java jpa map one-to-many
这似乎是一个常见的案例,但作为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;
.....
}
Run Code Online (Sandbox Code Playgroud)
我想我想使用@MapKeyJoinColumn注释,但我似乎无法使其他注释工作.我试过这个:
@OneToMany
@JoinColumn(name="ID")
@MapKeyJoinColumn(name="LOCALE")
private Map<String, Secondary> secondaryByLocale;
Run Code Online (Sandbox Code Playgroud)
这导致它尝试选择一个名为secondaryByLocale_key的列,该列不存在.
然后我尝试了这个:
@OneToMany
@JoinTable(name="SECONDARY",
joinColumns={@JoinColumn(name="ID")},
inverseJoinColumns=@JoinColumn(name="ID"))
@MapKeyJoinColumn(name="LOCALE")
private Map<String, Secondary> secondaryByLocale;
Run Code Online (Sandbox Code Playgroud)
这会导致以下错误:
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.
Run Code Online (Sandbox Code Playgroud)
我尝试将referencedColumnName添加到注释中(我不确定它应该是什么),但是我得到了同样的错误.
如建议的那样,我尝试使用@MapKey如下:
@OneToMany
@JoinColumn(name="ID")
@MapKey(name="LOCALE")
private Map<String, Secondary> secondaryByLocale;
Run Code Online (Sandbox Code Playgroud)
这会导致以下错误:
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]].
Run Code Online (Sandbox Code Playgroud)
也许我认为这一切都错了,并且有更好的方法来注释Map字段.任何帮助将非常感激.