简体   繁体   中英

Is it possible to map a map<String,List<Entity>> in JPA?

I'm thinking if i use maps like Map<String,List<Entity>> or Map<Long,List<Entity>> it will help me with a few things, but I couldn't find any example to map that kind of map.

My question is, is it possible to do that kind of mapping in JPA standards, and what kind of annotation I should use?

The answer is apparently no, as per link in the comment to original post and I can also confirm that it does not work in Eclipselink from what I tried.

I tried to do a nested Map<String, List<>> where key would be an ISO2 language code which would help retreiving only a specific subset of child relations which satisfy the current language context.

Something like this:

public class ProductEntity {

  @MapKey(name = "language")
  @OneToMany(mappedBy = "product", cascade = CascadeType.ALL, orphanRemoval = true,   fetch = FetchType.LAZY)
  private Map<String, List<AttributeEntity>> attributes;

}

public class AttributeEntity {

  private String language;

  @ManyToOne
  @JoinColumn(name="product_id")
  private ProductEntity product;
}

This would be useful when you need to retreive attributes for a specific language (coming from REST Accept-Language header for example) since you could just getAttributes().get(currentLanguage) instead of writing NamedQueries or do stream filtering.

At least for Eclipselink, I got a nonsensical error when I attempted this:

IllegalArgumentException: Object: [com.my.project.AttributeEntity@745f] is not a known Entity type.

Perhaps Hibernate has some tricks to support this but I didn't test it. My guess would be - no.

Yes, it's possible to create either of those Maps. Why not try it and answer your own question? It would be faster than passively asking here.

As for JPA, I would suggest a better abstraction than a Map for holding onto that data. This feels too generic for me. That might be what you're going for, but JPA ORM ought to map to a more robust object model than collections.

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