关于hibernate解析命名参数(named parameter)

最近因为要写一个自定义报表,所以需要把SQL的named parameter 匹配前台传过来的parameter,所以需要解析SQL获取里面的命名参数,然后就去研究hibernate怎么解析的,非常简单.hibernate源码我就不提供了(源码在:org.hibernate.engine.query.ParameterParser),下面提供精简过后的代码:
import java.util.ArrayList;

public class Test {

	public static void main(String[] args)
	{
		ArrayList<String> al = new ArrayList<String>();
		Test.parse("select * from sdf where a = :中文 and a >= to_date(:date,'yyyy-mm-dd hh24:mi:ss')", al);
		System.out.println("ssssss");
	}
	
	public static void parse(String sqlString,ArrayList<String> params){
		int stringLength = sqlString.length();
		boolean inQuote = false;
		for ( int indx = 0; indx < stringLength; indx++ ) {
			char c = sqlString.charAt( indx );
			if ( inQuote ) {\\如果标记为true,那么一直循环到结束的'
				if ( '\'' == c ) {
					inQuote = false;
				}
			}
			else if ( '\'' == c ) {\\这里第一次遇到'的时候打标记
				inQuote = true;
			}
			else if ( c == ':' ) {
				// named parameter
				int right = firstIndexOfChar( sqlString, " \n\r\f\t,()=<>&|+-=/*'^![]#~\\", indx + 1 );
				int chopLocation = right < 0 ? sqlString.length() : right;
				String param = sqlString.substring( indx + 1, chopLocation );
				if ( param == null || param.length() == 0) {
					throw new RuntimeException("Space is not allowed after parameter prefix ':' '"
							+ sqlString + "'");
				}
				params.add(param);
				indx = chopLocation - 1;
			}
			
		}
	}
	
	public static int firstIndexOfChar(String sqlString, String string, int startindex) {
		int matchAt = -1;
		for ( int i = 0; i < string.length(); i++ ) {
			int curMatch = sqlString.indexOf( string.charAt( i ), startindex );
			if ( curMatch >= 0 ) {
				if ( matchAt == -1 ) { // first time we find match!
					matchAt = curMatch;
				}
				else {
					matchAt = Math.min( matchAt, curMatch );
				}
			}
		}
		return matchAt;
	}
}

以上代码比较简单,不解释了.

你可能感兴趣的:(sql,C++,c,Hibernate,C#)