我正在使用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 );
说实话,我不知道如何使用Criteria返回关联的连接。我在这里寻找答案,但找不到答案:http://docs.jboss.org/hibernate/orm/3.3/reference/en/html/querycriteria.html,有人能帮帮我吗?一点点解释都会很棒。
答案 0 :(得分: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.