createSqlQuery Hibernate,Java

时间:2013-03-30 03:01:50

标签: java hibernate

我需要在Java领域编写hibernate查询(createSQLquery) 我有查询,但我有点失去了如何为我的查询创建标准。

基本上我必须将常规where子句转移到hibernate .add(限制)

例如,让我们:

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

由于现在无法访问我的环境,我没有机会运行它,只是想知道这个。

由于

2 个答案:

答案 0 :(得分: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());

答案 1 :(得分: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;
}