【问题标题】:HQL with a collection in the WHERE clause在 WHERE 子句中带有集合的 HQL
【发布时间】:2010-12-18 02:13:39
【问题描述】:

我一直在尝试询问谁正式让我做噩梦。该系统是一个用户和联系人管理。所以我有UserAccountContactPhone

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>();

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 中的集合。感谢阅读

【问题讨论】:

    标签: java hibernate jakarta-ee hql


    【解决方案1】:

    HQL 查询可能是这样的:

    选择 c 来自联系人 c 加入 c.phones cphones 其中 c.userAccount.email = :email 和 cphones.formatedNumber = :number

    您也可能希望像这样处理查询结果。 list() 方法总是返回一个列表,而不是 null。

     return !result.isEmpty();
    

    【讨论】:

    • return !result.isEmpty(); ;)
    猜你喜欢
    • 1970-01-01
    • 2016-07-01
    • 2011-06-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-02-12
    • 1970-01-01
    相关资源
    最近更新 更多