View Javadoc
1   /*******************************************************************************
2    *   Gisgraphy Project 
3    * 
4    *   This library is free software; you can redistribute it and/or
5    *   modify it under the terms of the GNU Lesser General Public
6    *   License as published by the Free Software Foundation; either
7    *   version 2.1 of the License, or (at your option) any later version.
8    * 
9    *   This library is distributed in the hope that it will be useful,
10   *   but WITHOUT ANY WARRANTY; without even the implied warranty of
11   *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
12   *   Lesser General Public License for more details.
13   * 
14   *   You should have received a copy of the GNU Lesser General Public
15   *   License along with this library; if not, write to the Free Software
16   *   Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA
17   * 
18   *  Copyright 2008  Gisgraphy project 
19   *  David Masclet <davidmasclet@gisgraphy.com>
20   *  
21   *  
22   *******************************************************************************/
23  package com.gisgraphy.hibernate.criterion;
24  
25  import org.hibernate.Criteria;
26  import org.hibernate.HibernateException;
27  import org.hibernate.criterion.CriteriaQuery;
28  import org.hibernate.criterion.Order;
29  import org.hibernate.util.StringHelper;
30  
31  /**
32   * @author <a href="mailto:david.masclet@gisgraphy.com">David Masclet</a> An
33   *         hibernate order for SQL
34   */
35  public class NativeSQLOrder extends Order {
36      /*
37       * (non-Javadoc)
38       * 
39       * @see org.hibernate.criterion.Order#toSqlString(org.hibernate.Criteria,
40       *      org.hibernate.criterion.CriteriaQuery)
41       */
42      @Override
43      public String toSqlString(Criteria criteria, CriteriaQuery criteriaQuery)
44  	    throws HibernateException {
45  	StringBuilder fragment = new StringBuilder();
46  	fragment.append("(");
47  	fragment.append(sql);
48  	fragment.append(")");
49  	fragment.append(ascending ? " asc" : " desc");
50  	return StringHelper.replace(fragment.toString(), "{alias}",
51  		criteriaQuery.getSQLAlias(criteria));
52      }
53  
54      private static final long serialVersionUID = 1L;
55  
56      private boolean ascending;
57      private String sql;
58  
59      /**
60       * @param sql
61       *                the sql code
62       * @param ascending
63       *                whether we want to sort asc or desc
64       */
65      public NativeSQLOrder(String sql, boolean ascending) {
66  	super(null, ascending);
67  	this.sql = sql;
68  	this.ascending = ascending;
69  
70      }
71  
72      /**
73       * @param sql
74       *                the sql code Default sorting will be ascending
75       */
76      public NativeSQLOrder(String sql) {
77  	super(null, true);
78  	this.sql = sql;
79  	this.ascending = true;
80  
81      }
82  
83  }