2012-08-02 56 views
0

我有标签对象和Price对象以及标签列表。我可以找到一个指定标签的价格,但我不知道如何编写查询来查找价格,并给出如下标签列表:find price where price.tags = blue,red,green。结果必须包含所有名称分别为蓝色,红色和绿色的标签。JPA查找具有给定标签列表的实体

@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(); 
    } 

} 

回答

0

您需要在标签中声明关系的另一端。 您还需要通过Proce @ManyToMany映射的用户来定义关系的“主”。

查看示例here