有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

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

我正在使用PlayFramework(java)1.2.4、jpa和hibernate。发生查找错误时,如何检查关系(oneToMany)模型字段值

控制模式:

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

控制器:

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

当我检查状态表值(oneToMany)时,出现以下错误:

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

共 (2) 个答案

  1. # 1 楼答案

    方法find也支持正常的JPQL查询。以下是获取唯一国家列表的替代品,这些国家的状态为product_id 5:

    SELECT DISTINCT(s.country) FROM States s WHERE s.product_id = 5
    
  2. # 2 楼答案

    我认为这样的方法会奏效,尽管它还没有经过测试

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

    我忘了,你可能需要5点左右的报价。你也可以使用join子句,但我认为这在这里没有必要

    此外,你的模特名字应该是单数,而不是复数。这会让你困惑。这让我困惑:-)