2016-12-27 77 views
1

我需要選擇鏈接租借實體的所有字段return_date爲空的客戶記錄。下面的SQL查詢工作:帶有內部連接的HQL查詢並檢查NULL失敗

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元素,以便您可以反轉查詢,從RENTAL對象(我希望你映射它)

試試這個:

Query query = session.createQuery("select c " + 
      " from Rental r, Customer c " + 
      " where r.customer_id = c.customer_id " + 
      " and r.return_date is null"); 
+0

第一個不適用,第二個不起作用。 –

+0

請發佈第二個查詢的錯誤?第一,爲什麼不適用? –

+0

你的第二個查詢甚至不會擊中'BREAKPOINT A'。確實奇怪.. –