我需要选择已链接租用实体的所有客户记录,该实体的字段return_date
为空。以下SQL查询有效:
SELECT
c.customer_id, r.rental_id
FROM
Customer c
INNER JOIN rental as r
ON (c.customer_id = r.customer_id)
WHERE r.return_date IS NULL;
为什么以下HQL无效:
Query query = session.createQuery("from Customer customer " +
"inner join customer.rentals as r " +
"where r.return_date is null");
上下文:
@Override
public List<Customer> getFilteredCustomers(String filter) {
Session session = null;
List<Customer> customers = new ArrayList<>();
try {
session = sessionFactory.openSession();
Query query = session.createQuery("select customer from Customer customer " +
"join customer.rentals r " +
"where r.return_date is null");
customers = (List<Customer>)query.list(); // << BREAKPOINT A
}catch (Exception e){
System.out.println(e);
}finally {
if (session!=null) session.close();
}
return customers;
}
解决方案:
显然,HQL中使用的字段名称必须取自模型类,而不是来自数据库......
Query query = session.createQuery("select c " +
" from Rental r, Customer c " +
" where r.customer = c " +
" and r.returnDate is null");
答案 0 :(得分:0)
您的查询不起作用,因为您尝试将客户与集合(租赁)链接,但要在return_date上访问,您必须指向集合的i-esime元素,以便您可以反转查询,从{{1开始对象(我希望你已经映射了它)
试试这个:
RENTAL