我有一个实体产品:
@OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY, mappedBy = "product")
@MapKeyColumn(name="locale")
public Map<String,ProductNames> getProductNames() {
return this.productNames;
}
以及一个名为productNames 的实体,其中包含产品的本地化版本
private int id;
private SkiProduct skiProduct;
private String locale;
private String text;
我尝试了@MapKeyColumn
和@MapKey
注释。
生成的 SQL 如下所示:
select
productnam0_.product_id as product4_1_,
productnam0_.id as id1_,
productnam0_.mapkey as mapkey1_,
productnam0_.id as id231_0_,
productnam0_.locale as locale231_0_,
productnam0_.product_id as product4_231_0_,
productnam0_.text as text231_0_
from
product_names productnam0_
我的问题是如何正确配置此映射。 SQL 语句中的映射键列会导致 SQL-Errormsg,因为它不在数据库表中。
Type (ROW(id integer, locale char(2), text varchar(255), product_id integer)) not found.
编辑:Javadoc说:“如果将主键以外的持久字段或属性用作映射键,那么它应该具有与其关联的唯一性约束。”
所以我想知道是否可以使用 map 来实现此目的?
最佳答案
Map 键在 Java 中应该是唯一的,这反射(reflect)在 JPA 中期望数据库中的唯一键映射到 Map 的键。 如果您不能保证唯一性,则需要使用其他数据结构或使用其他 key 。
如果可能,在您想要作为键的字段上设置一个唯一键,这应该可以解决您的问题(但您可能最终必须使用复合键,因此在 Java 代码中使用不同的 Map 结构,例如您可能有一个唯一的 mapkey+language_id 复合键)。
关于java - 如何使用 JPA 映射具有本地化产品名称的表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5078364/