简体   繁体   中英

How to Map a Table with localized Product Names using JPA?

I have an entity product:

@OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY, mappedBy = "product")
@MapKeyColumn(name="locale")
public Map<String,ProductNames> getProductNames() {
    return this.productNames;
}

and an entity named productNames which contains the localized versions of the product

private int id;
private SkiProduct skiProduct;
private String locale;
private String text;

I tried the @MapKeyColumn and the @MapKey annotation. The generated SQL looks like this:

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_

My question is how to configure this mapping correctly. The mapkey column in the SQL-statement leads to a SQL-Errormsg since it is not in the db-table.

Type (ROW(id integer, locale char(2), text varchar(255), product_id integer)) not found.

EDIT: The Javadoc says: "If a persistent field or property other than the primary key is used as a map key then it is expected to have a uniqueness constraint associated with it. "

So I wonder whether I could use Maps for this ?

A Map key is supposed to be unique in Java, and that's reflected in JPA expecting a unique key in the database to map to the key for the Map. If you can't guarantee that uniqueness, you need to use another datastructure or use another key.

If possible, set up a unique key on the fields you want to be the key, that should fix your problem (but you would possibly end up having to use a compound key, and thus a different Map structure in your Java code, for example you might have a mapkey+language_id compound key that's unique).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM