[英]Mapping a Map<String,List<Foo>> in Hibernate
Considering the following object: 考虑以下对象:
Keyword{
int id;
String area;
String keyword;
Article article;
}
What is the best way to Map the following association in Hibernate, where the map's key should be Keyword.area: 在Hibernate中映射以下关联的最佳方法是什么,映射的键应为Keyword.area:
Article{
private Map<String,List<Keyword>> keywords = new HashMap<String, List<Keyword>>();
}
It is straightforward if it was a Map, but in this situation I will mostly need to access the keywords by area (eg article.findAll("science") to return all science keywords). 如果它是Map,这很简单,但是在这种情况下,我将最需要按区域访问关键字(例如,article.findAll(“ science”)以返回所有科学关键字)。
The best idea I've had so far is to transform the former into 到目前为止,我最好的想法是将前者转变为
private Map<String,KeywordGroup> keywords = new HashMap<String, KeywordGroup>();
but this leaves me with some questions, like: 但这给我留下了一些问题,例如:
What approach would you suggest? 您会建议哪种方法?
I think the following implementation of Article would work for you, without the need for a Map. 我认为以下Article的实现将为您工作,而无需使用Map。
@Entity
public class Article {
@OneToMany(mappedBy="article")
private Set<Keyword> keywords;
//..
public Set<Keyword> findKeywordsByArea(String area) {
Set<Keyword> matchingKeywords = new HashSet<Keyword>();
for(Keyword keyword : this.keywords) {
if(keyword.getArea().equals(area)) {
matchingKeywords.add(keyword);
}
}
return matchingKeywords;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.