package com.awsle.aibatis.sql;
|
|
import java.util.ArrayList;
|
import java.util.List;
|
import java.util.Map;
|
|
import com.awsle.aibatis.reflect.ObjectUtils;
|
|
/**
|
*
|
* @author 席有芳
|
* @url http://code.awsle.com/index.php/p/aibatis/
|
* @mail 951868171@qq.com
|
* @version 1.0
|
* @since aibatis-Alpha1.0.zip
|
*/
|
public class DynamicSql {
|
|
private String sql;
|
|
private List params;
|
|
private String[] bindArgs;
|
|
private DynamicSql(){
|
setParams(new ArrayList());
|
}
|
|
/**
|
* 解析动态SQL
|
* @param abatisSql
|
* @return
|
*/
|
public static DynamicSql parser(String abatisSql){
|
DynamicSql dynamicSql = new DynamicSql();
|
StringBuffer bodyContent = new StringBuffer(abatisSql);
|
iteratePropertyReplace(bodyContent,dynamicSql.getParams());
|
dynamicSql.setSql(bodyContent.toString());
|
return dynamicSql;
|
}
|
|
/**
|
*
|
* @param bodyContent
|
* @param list
|
*/
|
private static void iteratePropertyReplace(StringBuffer bodyContent,List list) {
|
|
int startIndex = 0;
|
int endIndex = -1;
|
while (startIndex > -1 && startIndex < bodyContent.length()) {
|
startIndex = bodyContent.indexOf("#");
|
endIndex = bodyContent.indexOf("#", startIndex + 1);
|
if (startIndex > -1 && endIndex > -1) {
|
list.add(bodyContent.subSequence(startIndex+1, endIndex));
|
bodyContent.replace(startIndex, endIndex+1, "?");
|
|
}
|
|
}
|
|
}
|
|
public String getSql() {
|
return sql;
|
}
|
|
public void setSql(String sql) {
|
this.sql = sql;
|
}
|
|
public List getParams() {
|
return params;
|
}
|
|
public void setParams(List params) {
|
this.params = params;
|
}
|
|
public String[] getBindArgs() {
|
return bindArgs;
|
}
|
|
public void setBindArgs(String[] bindArgs) {
|
this.bindArgs = bindArgs;
|
}
|
|
public void buildBindArgs(Object parameterObject) {
|
if(parameterObject == null){
|
return ;
|
}
|
int size = params.size();
|
bindArgs = new String[size];
|
if(parameterObject instanceof Map){
|
Map<String, String> map = (Map<String, String>) parameterObject;
|
for (int i =0 ; i< size ; i++){
|
bindArgs[i] = map.get(params.get(i));
|
}
|
}
|
|
else if(parameterObject instanceof String){
|
for (int i =0 ; i< size ; i++){
|
bindArgs[i] = parameterObject.toString();
|
}
|
}
|
//普通java bean
|
else {
|
Map map = ObjectUtils.objectToMap(parameterObject);
|
for (int i =0 ; i< size ; i++){
|
Object value = map.get(params.get(i));
|
if(value instanceof Integer){
|
bindArgs[i] = String.valueOf(value);
|
}
|
else{
|
bindArgs[i] = value.toString();
|
}
|
|
}
|
}
|
|
}
|
|
}
|