0

我正在使用 HQL 进行动态查询,但由于参数很多,我相信 Criteria 会更加“可读”。查询如下所示:

String queryString = "select u from ReportSalesUnit as r join r.recipients as u where r.id = :reportSalesUnitId";
if ( firstName != null )
{
    queryString += " and lower(u.firstName) like :firstName";
}
if ( lastName != null )
{
    queryString += " and lower(u.lastName) like :lastName";
}
if ( email != null )
{
    queryString += " and lower(u.email) like :email";
}
if ( phoneNr != null )
{
    queryString += " and u.phoneNr like :phoneNr";
}
Query query = session.createQuery( queryString );
if ( firstName != null )
{
    query.setParameter( "firstName", firstName.toLowerCase() + "%" );
}
if ( lastName != null )
{
    query.setParameter( "lastName", lastName.toLowerCase() + "%" );
}
if ( email != null )
{
    query.setParameter( "email", email.toLowerCase() + "%" );
}
if ( phoneNr != null )
{
    query.setParameter( "phoneNr", phoneNr + "%" );
}
query.setParameter( "reportSalesUnitId", reportSalesUnitId );

老实说,我不知道如何返回与标准相关的联接。我在这里寻找答案,但找不到答案: http: //docs.jboss.org/hibernate/orm/3.3/reference/en/html/querycriteria.html,有人可以帮我吗?一点解释会很棒。

4

1 回答 1

0

标准也可以这样使用:

...
if(firstName != null) {   
   criteria.add(Restrictions.and(
      Restrictions.isNotNull("firstName"), Restrictions.eq("firstName", firstName.toLowerCase());
...

看起来,它不会因为许多条件而变得更具可读性。但Criteria可以通过这种方式帮助您:

Criteria在到达/Query创建之前,您应该预先检查 null(或其他异常) 。最后,您将获得如下代码,我想这对您来说是可以接受的:

... 
criteria.add(Restrictions.eq("firstName", firstName.toLowerCase()));
criteria.add(Restrictions.eq("phoneNr", phoneNr));
...
criteria.list();

而且,您可以通过这样的别名创建连接或获取数据:

criteria.createAlias("recipients", "recipients", JoinType.LEFT_OUTER_JOIN);

或者

criteria.createAlias("recipients", "recipients");
        .setFetchMode("recipients", FetchMode.JOIN);

according to your needs.
于 2012-10-23T11:40:43.703 回答