我有带有标签列表的 Tag 对象和 Price 对象。我可以找到带有一个指定标签的价格,但我不知道如何编写查询来查找带有给定标签列表的价格,例如:find price where price.tags=blue,red,green。结果必须包含名为 blue、red 和 green 的所有标签。
@Entity
@Inheritance(strategy = InheritanceType.SINGLE_TABLE)
public class Tag extends Model implements Comparable<Tag>{
public String name;
public Tag(){
}
public Tag(String name) {
this.name = name;
}
public static Tag findOrCreateByName(String name) {
Tag tag = Tag.find("byName", name).first();
if(tag == null) {
tag = new Tag(name);
}
return tag;
}
@Override
public int compareTo(Tag otherTag) {
return name.compareTo(otherTag.name);
}
}
@Entity
@Inheritance(strategy = InheritanceType.SINGLE_TABLE)
public class Price extends Model{
@Min(0.0)
public float price;
@ManyToMany
public List<Tag> tags;
public Price() {
this.tags = new ArrayList<Tag>();
}
public Price(int price) {
this.price = price;
this.tags = new ArrayList<Tag>();
}
public Price tagItWith(String name) {
tags.add(Tag.findOrCreateByName(name));
return this;
}
public static List<Price> findTaggedWith(String tag) {
return Price.find(
"select distinct p from Price p join p.tags as t where t.name = ?", tag
).fetch();
}
}