如何在jpa中检查一对多关系模型字段值中的条件

时间:2013-02-18 06:08:22

标签: java hibernate jpa playframework

我正在使用play framework(java)1.2.4,jpa和hibernate.How我可以检查关系(oneToMany)模型字段值查找发生错误

Contry模型:

@Entity
public class Countries extends Model {

    @Required
    public String name;

    public String iso2;

    public String iso3; 

    @OneToMany(mappedBy="country", fetch=FetchType.EAGER,  cascade=CascadeType.All)
    public List<States> states;

    public Countries() { }

}

州模式:

@Entity
public class States extends Model {

   @Required
   public long country_id;

   @Required
   public String name;  

   @Required
   public long product_id; 

   @ManyToOne(fetch=FetchType.EAGER)
   @NotFound(action = NotFoundAction.IGNORE)
   @JoinColumn(name="country_id", nullable=false,insertable=false, updatable=false)
   public Countries country;

   public States() { }
}

在Contry控制器中:

   List<Countries> countries = Countries.find("states.product_id =5").fetch(); 

当我检查状态表值(oneToMany)后发生错误:

    IllegalArgumentException occured : org.hibernate.QueryException: illegal attempt to dereference collection 

2 个答案:

答案 0 :(得分:0)

我觉得这样的东西会起作用,虽然没有经过考验。

List<Countries> countries = Countries.find(
    "select c from Countries c, States s where s.country = c and s.product_id = ?", 5
);

你可能需要5左右的报价,我忘了。您也可以使用join子句来完成它,但我认为这不是必需的。

此外,您的模型名称应该是单数,而不是复数。这应该让你感到困惑。这让我很困惑: - )

答案 1 :(得分:0)

方法find也支持普通的JPQL查询。以下是直接替换以获取具有product_id 5状态的唯一国家/地区列表:

SELECT DISTINCT(s.country) FROM States s WHERE s.product_id = 5