我正在使用JPA和JPQL。使用JPQL我想获取加入一个集合,该集合是“主要”实体租金的属性。这是我的源代码:
public Rent getRentWithAllDetails(Rent rent) {
Query queryString = em.createQuery(" select r from Rent r JOIN FETCH r.rentables where r.id = :rid").setParameter(1, rent.getId());
List <Rent> resultList = queryString.getResultList();
return resultList.get(0);
}
这是我收到的例外:
Caused by: java.lang.IllegalArgumentException: Parameter with that position [1] did not exist
at org.hibernate.jpa.spi.BaseQueryImpl.findParameterRegistration(BaseQueryImpl.java:518) [hibernate-entitymanager-4.3.7.Final.jar:4.3.7.Final]
at org.hibernate.jpa.spi.BaseQueryImpl.setParameter(BaseQueryImpl.java:674) [hibernate-entitymanager-4.3.7.Final.jar:4.3.7.Final]
at org.hibernate.jpa.spi.AbstractQueryImpl.setParameter(AbstractQueryImpl.java:198) [hibernate-entitymanager-4.3.7.Final.jar:4.3.7.Final]
at org.hibernate.jpa.spi.AbstractQueryImpl.setParameter(AbstractQueryImpl.java:49) [hibernate-entitymanager-4.3.7.Final.jar:4.3.7.Final]
有人可以帮助我吗?
答案 0 :(得分:3)
您正在使用命名参数,因此您应该在创建查询时使用该名称绑定参数:
String sql = "select r from Rent r JOIN FETCH r.rentables where r.id = :rid";
Query queryString = em.createQuery(sql)
.setParameter("rid", rent.getId());
List<Rent> resultList = queryString.getResultList();
答案 1 :(得分:1)
请将您的代码更改为:
public Rent getRentWithAllDetails(Rent rent) {
Query queryString = em.createQuery(" select r from Rent r JOIN FETCH r.rentables where r.id = :rid").setParameter("rid", rent.getId());
List <Rent> resultList = queryString.getResultList();
return resultList.get(0);
}
如果多次重复rid
,则可以相应地使用0,1..etc,否则请使用参数名称。