1

我需要在 Java 中编写休眠查询 (createSQLquery) 我有查询但我有点迷失了如何为我的查询创建条件。

基本上我必须将常规 where 子句转移到休眠 .add(Restriction)

例如让我们采取:

where (name LIKE '%test%' or lastname LIKE '%test%') and (site_id = 2) and (date>=121212 and date <= 343343)

Query query = sess.createSQLQuery(sql).addScalar("ID", Hibernate.long);
query.add(Restrictions.or ( 
                            Restrictions.like("name", "%test%")
                            Restrictions.like("lastname", "Fritz%")
          ))
     .add(Restrictions.eq("site_id", new Integer(2)))
     .add(Restrictions.add(Restrictions.gr("date_start", 122122)
                       .add(Restrictions.le("date_end", 345433)));

我没有机会运行它,因为现在无法访问我的环境,只是想弄清楚这一点。

谢谢

4

2 回答 2

0

你必须这样做

    Criteria criteria = session.createCriteria(YourPojo.class);
    criteria.add(Restrictions.eq("id", id));
    criteria .add(Restrictions.or ( 
                        Restrictions.like("name", "%test%"),
                        Restrictions.like("lastname", "Fritz%")));
    criteria.add(Restrictions.eq("site_id", new Integer(2)))
    criteria.add(Restrictions.add(Restrictions.gr("date_start", 122122)
                   .add(Restrictions.le("date_end", 345433)));
    return (criteria.list());
于 2013-03-30T07:42:15.987 回答
0

好的,问题这样解决了:

从 XML 查询 - 我放入 where 子句

<Applications>
    <Application name="AlertData">
        <Query name="alerts">
            <SQL>
                SELECT 
                    mr.measurement_date as measurementDate,
                    ........ // more data
                FROM measurement m
                    LEFT JOIN tags     ON mr.tag_id = tags.tag_id
                    .......... // more joins
                WHERE
                    mr.site_id = :siteid
                    $searchConstraints$ // just a string
                    $dateStartFragment$ // just a string                                  
            </SQL>
        </Query>
    </Application>
</Applications>

下一个 Java 代码:

 if (search != null && !search.isEmpty()) {   
            searchFragment = " AND (UPPER(field1) LIKE :search" +
                              " OR UPPER(field2)  LIKE :search)";           
  }


  sql = this.prepareQuery(sql, ImmutableMap.of(
      "searchConstraints", searchFragment,
      "dateStartFragment", dateStartFragment
  ));


   Query query = this.sessionFactory.getCurrentSession()
                .createSQLQuery(sql) 
   //more query here



 if (search != null && !search.isEmpty()) {    
     query.setString("search", "%" + search.toUpperCase() + "%");            
 }



public String prepareQuery(String queryString, Map<String, String> templateVars) {
     ST stringTemplater = new ST(queryString, '$', '$');

      for (String key : templateVars.keySet()) {
          stringTemplater.add(key, templateVars.get(key));
      }

      String renderedQuery = stringTemplater.render();
      return renderedQuery;
}
于 2013-04-02T23:53:33.890 回答