1 16 package com.ibatis.sqlmap.engine.mapping.sql.simple; 17 18 import com.ibatis.common.beans.Probe; 19 import com.ibatis.common.beans.ProbeFactory; 20 import com.ibatis.sqlmap.client.SqlMapException; 21 import com.ibatis.sqlmap.engine.impl.SqlMapExecutorDelegate; 22 import com.ibatis.sqlmap.engine.mapping.parameter.ParameterMap; 23 import com.ibatis.sqlmap.engine.mapping.result.ResultMap; 24 import com.ibatis.sqlmap.engine.mapping.sql.Sql; 25 import com.ibatis.sqlmap.engine.scope.RequestScope; 26 27 import java.util.StringTokenizer ; 28 29 public class SimpleDynamicSql implements Sql { 30 31 private static final Probe PROBE = ProbeFactory.getProbe(); 32 33 private static final String ELEMENT_TOKEN = "$"; 34 35 private String sqlStatement; 36 37 private SqlMapExecutorDelegate delegate; 38 39 public SimpleDynamicSql(SqlMapExecutorDelegate delegate, String sqlStatement) { 40 this.delegate = delegate; 41 this.sqlStatement = sqlStatement; 42 } 43 44 public String getSql(RequestScope request, Object parameterObject) { 45 return processDynamicElements(sqlStatement, parameterObject); 46 } 47 48 public ParameterMap getParameterMap(RequestScope request, Object parameterObject) { 49 return request.getParameterMap(); 50 } 51 52 public ResultMap getResultMap(RequestScope request, Object parameterObject) { 53 return request.getResultMap(); 54 } 55 56 public void cleanup(RequestScope request) { 57 } 58 59 public static boolean isSimpleDynamicSql(String sql) { 60 return sql != null && sql.indexOf(ELEMENT_TOKEN) > -1; 61 } 62 63 private String processDynamicElements(String sql, Object parameterObject) { 64 StringTokenizer parser = new StringTokenizer (sql, ELEMENT_TOKEN, true); 65 StringBuffer newSql = new StringBuffer (); 66 67 String token = null; 68 String lastToken = null; 69 while (parser.hasMoreTokens()) { 70 token = parser.nextToken(); 71 72 if (ELEMENT_TOKEN.equals(lastToken)) { 73 if (ELEMENT_TOKEN.equals(token)) { 74 newSql.append(ELEMENT_TOKEN); 75 token = null; 76 } else { 77 78 Object value = null; 79 if (parameterObject != null) { 80 if (delegate.getTypeHandlerFactory().hasTypeHandler(parameterObject.getClass())) { 81 value = parameterObject; 82 } else { 83 value = PROBE.getObject(parameterObject, token); 84 } 85 } 86 if (value != null) { 87 newSql.append(String.valueOf(value)); 88 } 89 90 token = parser.nextToken(); 91 if (!ELEMENT_TOKEN.equals(token)) { 92 throw new SqlMapException("Unterminated dynamic element in sql (" + sql + ")."); 93 } 94 token = null; 95 } 96 } else { 97 if (!ELEMENT_TOKEN.equals(token)) { 98 newSql.append(token); 99 } 100 } 101 102 lastToken = token; 103 } 104 105 return newSql.toString(); 106 } 107 108 109 } 110 111
| Popular Tags
|