hibernate QueryException:无法解析spring petclinic示例应用程序中的属性

时间:2013-09-05 23:02:20

标签: java spring hibernate jpa

我有以下JPA方法:

@SuppressWarnings("unchecked")
public Collection<Owner> findByPetType(Integer typeID) {
    Query query = this.em.createQuery("SELECT DISTINCT owner FROM Owner owner left join fetch owner.pets as pet WHERE pet.type_id LIKE :typeID");
    query.setParameter("typeID", typeID + "%");
    return query.getResultList();
}  

它抛出以下错误消息:

org.hibernate.QueryException: could not resolve property: type_id of:  
org.springframework.samples.petclinic.model.Pet [SELECT DISTINCT owner FROM  
org.springframework.samples.petclinic.model.Owner owner left join fetch owner.pets  
as pet WHERE pet.type_id LIKE :typeID];  
nested exception is java.lang.IllegalArgumentException:  
org.hibernate.QueryException: could not resolve property: type_id of:  
org.springframework.samples.petclinic.model.Pet [SELECT DISTINCT owner FROM      
org.springframework.samples.petclinic.model.Owner owner left join fetch owner.pets  
as pet WHERE pet.type_id LIKE :typeID]  

这是来自Spring petclinic示例应用程序,因此所有相关代码is at this link,包括数据库定义。我使用的是hsqldb和jpa,上面的findByPetType()方法是我写的,不在示例应用程序中。

任何人都可以告诉我如何修复代码,以便它不会产生此错误消息吗?

编辑:

我遵循Alex的建议并将pet.type_id更改为pet.type。现在它给我以下错误消息(typeID的值设置为1):

Parameter value [1%] did not match expected type  
[org.springframework.samples.petclinic.model.PetType]; nested exception is  
java.lang.IllegalArgumentException: Parameter value [1%] did not match expected type  
[org.springframework.samples.petclinic.model.PetType]  

第二次编辑:

我提出了Sergi Almar的建议,现在它抛出了以下错误:

Parameter value [1%] did not match expected type [java.lang.Integer]; nested exception   
is java.lang.IllegalArgumentException: Parameter value [1%] did not match expected type   
[java.lang.Integer]  

我检查过,调用代码将typeID作为“Integer typeID = 1;”启动所以我不确定为什么这里没有看到整数。

2 个答案:

答案 0 :(得分:4)

pet.type_id更改为pet.type。您必须在HQL中使用实体的映射属性(而不是列名称)。

答案 1 :(得分:4)

由于这是一个JPQL查询,您应该在查询中使用实体属性(Pet有一个具有id的PetType)。以下代码将按预期执行:

@SuppressWarnings("unchecked")
public Collection<Owner> findByPetType(Integer typeID) {
     Query query = this.em.createQuery("SELECT DISTINCT owner FROM Owner owner left join fetch owner.pets as pet WHERE pet.type.id = :typeID");
    query.setParameter("typeID", typeID);
    return query.getResultList();
}