我有以下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()方法是我写的,但不在示例应用程序中。
谁能告诉我如何修复代码,以免产生此错误消息?
编辑:
我按照亚历克斯的建议,将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;”。因此,我不确定为什么在这里看不到整数。
最佳答案
由于这是一个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();
}