2009-11-18 87 views
9

我一直在嘗試爲整個查詢誰正式給我噩夢。該系統是一個用戶和聯繫人管理。所以我有UserAccount,ContactPhoneHQL與WHERE子句中的集合

UserAccountContact雙向一個一對多的關係,並在手機上的單向一個全部由Set映射:

//UserAccount mapping 
@OneToMany(targetEntity=PhoneImpl.class, cascade= {CascadeType.ALL}) 
@org.hibernate.annotations.Cascade(value=org.hibernate.annotations.CascadeType.DELETE_ORPHAN) 
private Set<Phone> phones = new HashSet<Phone>(); 

@OneToMany(targetEntity=ContactImpl.class, cascade={CascadeType.ALL}, mappedBy="userAccount") 
@org.hibernate.annotations.Cascade(value=org.hibernate.annotations.CascadeType.DELETE_ORPHAN) 
private Set<Contact> contacts = new HashSet<Contact>(); 

跟現在有一個一對多的單向與手機

@OneToMany(targetEntity=PhoneImpl.class, cascade={CascadeType.ALL}) 
private Set<Phone> phones = new HashSet<Phone>(); 

我正在寫一個方法來檢查電子郵件唯一字段中特定用戶的同一聯繫人是否存在相同的號碼。

我知道我可以覆蓋equalshashcode,但由於電話在一個實體映射的實體我不知道在這一刻該怎麼做。所以我想提供一種方法來聯繫頁面上的每個條目之前,而檢查是否有獨特性,我

public boolean checkForExistingPhone(String userEmail, String formatedNumber) { 
    List<Contact> result = null; 
    Session sess = getDBSession().getSession(); 

    String query = "select Contact ,cphones.formatedNumber from Contact c inner join Contact.phones cphones where c.UserAccount.email = :email and cphones.formatedNumber= :number"; 
//  try { 
     result = (List<Contact>) sess.createQuery(query) 
       .setParameter("email", userEmail) 
       .setParameter("number", formatedNumber).list(); 
//  } catch (HibernateException hibernateException) { 
//   logger.error("Error while fetching contacts of email " + userEmail + " Details:"  + hibernateException.getMessage()); 
//  } 
     if(result == null) 
      return false; 
     else 
      return true; 
} 

我繼續有這個錯誤:

org.hibernate.hql.ast.QuerySyntaxException: Contact is not mapped [select 
cphones.formatedNumber from Contact c inner join Contact.phones cphones where 
c.UserAccount.email = :email and cphones.formatedNumber= :number]. 

我真的不能弄清楚發生了什麼和第一我不知道如何處理在HSQ.thanks收藏閱讀

回答

16

HQL查詢是可能的東西沿着這些路線:

 
select c 
from Contact c 
join c.phones cphones 
where c.userAccount.email = :email 
    and cphones.formatedNumber = :number 

另外你可能想要處理這樣的查詢結果。 列表()方法總是返回一個列表,從不爲空。

return !result.isEmpty(); 
+0

或'返回result.isEmpty();!' ;) – 2009-11-19 15:10:02

+0

@ framer8,固定 – 2009-11-19 19:18:03