关于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;
}
}

以上代码比较简单,不解释了.
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值