ibatis实现动态sql处理

package base; import java.io.ByteArrayInputStream; import java.io.InputStream; import java.sql.Connection; import java.sql.ResultSet; import java.util.Calendar; import java.util.Date; import java.util.List; import java.util.Map; import javax.annotation.Resource; import org.junit.Test; import org.junit.runner.RunWith; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.orm.ibatis.SqlMapClientTemplate; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import com.google.common.collect.Lists; import com.google.common.collect.Maps; import com.ibatis.common.resources.Resources; import com.ibatis.sqlmap.engine.builder.xml.SqlMapParser; import com.ibatis.sqlmap.engine.builder.xml.XmlParserState; import com.ibatis.sqlmap.engine.mapping.parameter.ParameterMap; import com.ibatis.sqlmap.engine.mapping.result.ResultMap; import com.ibatis.sqlmap.engine.mapping.sql.Sql; import com.ibatis.sqlmap.engine.mapping.statement.MappedStatement; import com.ibatis.sqlmap.engine.scope.SessionScope; import com.ibatis.sqlmap.engine.scope.StatementScope; import com.wtt.unified.schedule.dal.base.dao.AlipayPushScheduleDAOImpl;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"classpath:test.xml"})
public class SqlSourceTest {
static Logger log = LoggerFactory.getLogger(SqlSourceTest.class.getName());
@Resource
private AlipayPushScheduleDAOImpl alipayPushScheduleDAO;

@Test 
public void test() throws Exception{
    StringBuilder stringBuilder = new StringBuilder();
    stringBuilder.append("<?xml version=\"1.0\" encoding=\"UTF-8\" ?>").append("\r\n");
    stringBuilder.append("<!DOCTYPE sqlMap PUBLIC \"-//ibatis.apache.org//DTD SQL Map 2.0//EN\" \"http://ibatis.apache.org/dtd/sql-map-2.dtd\" >").append("\r\n");
    stringBuilder.append("<sqlMap namespace=\"SimpleTaskSelectTemp_123\">").append("\r\n");
    stringBuilder.append("<select id=\"queryList\"  resultClass=\"java.util.HashMap\" parameterClass=\"java.util.Map\" >").append("\r\n");
    //修改掉
    stringBuilder.append("select            id as id,        gmt_create as gmtCreate,        gmt_modified as gmtModified,        alipay_id as alipayId,        phone_no as phoneNo,        balance as balance,        threshold as threshold,        gmt_warn_time as gmtWarnTime,        ext as ext,        audit_id as auditId").append(" from  alipay_push_schedule   where 1=1   <isNotNull property=\"startTime\" prepend=\" and\">")
    .append("    <![CDATA[ gmt_warn_time >= #startTime# ]]>  </isNotNull>")
    .append("    <isNotNull property=\"endTime\" prepend=\" and\">")
    .append("   <![CDATA[ gmt_warn_time <= #endTime# ]]>")
         .append(" </isNotNull> limit #limit#");
    stringBuilder.append("</select> ");
    
    stringBuilder.append("</sqlMap>");
    String  dsName ="";
    System.out.println(stringBuilder.toString());
    SqlMapClientTemplate template = alipayPushScheduleDAO.getTemplate();
    //方案二

// SQLSelectBuilder sqlBuilder = SQLBuilderFactory.createSelectSQLBuilder(JdbcConstants.MYSQL);
// sqlBuilder.select("")
// .from("");
//sqlMapClient

// InputStream inputStream = Resources.getResourceAsStream("AliPayPushScheduleTask_sqlmap.xml");
//
InputStream inputStream =new ByteArrayInputStream(stringBuilder.toString().getBytes());
String sql =null;
XmlParserState state = new XmlParserState();
SqlMapParser parser = new SqlMapParser(state);
parser.parse(inputStream);
MappedStatement mappedStatement = state.getConfig().getDelegate().getMappedStatement("queryList");
Sql stmtSql = mappedStatement.getSql();
Map<String,Object> map = Maps.newHashMap() ;
map.put("limit", 2);
map.put("startTime",getTimesmorning());

    ResultMap resultMap = mappedStatement.getResultMap();
    
    SessionScope sessionScope = new SessionScope();
    StatementScope requestScope = new StatementScope(sessionScope);
    requestScope.setStatement(mappedStatement);
    requestScope.setResultMap(resultMap);
    sql = stmtSql.getSql(requestScope, map);
    ParameterMap parameterMap = stmtSql.getParameterMap(requestScope, map);
    requestScope.setParameterMap(parameterMap);
    Object[] parameters = parameterMap.getParameterObjectValues(requestScope, map);
    java.sql.PreparedStatement ps = null;
    ResultSet rs = null;
    Connection conn = template.getDataSource().getConnection();
    
    Integer rsType = requestScope.getStatement().getResultSetType();
    if(rsType != null) {
        ps = conn.prepareStatement(sql, rsType.intValue(), 1007);
    } else {
        ps =conn.prepareStatement(sql);
    }
    //设置参数
    parameterMap.setParameters(requestScope, ps, parameters);

    ps.execute();
    rs = ps.getResultSet();
    int resultsFetched = 0;
    List<Map<String,Object>> list = Lists.newArrayList();
    while ( rs.next()) {
        Object[] columnValues = resultMap.resolveSubMap(requestScope, rs).getResults(requestScope, rs);

// callback.handleResultObject(statementScope, columnValues, rs);
Object object;
object = resultMap.resolveSubMap(requestScope, rs).setResultObjectValues(requestScope, null, columnValues);
list.add((Map<String,Object>) object);
System.out.println(object);
resultsFetched++;
}
for(Map<String,Object> m : list){
StringBuilder sb = new StringBuilder();
for(Map.Entry<String,Object> entry:m.entrySet()){
sb.append(entry.getKey()).append("|").append(entry.getValue()).append("&");
}
System.out.println(sb.toString());
}
System.out.println(sql);
System.out.println(parameterMap);
rs.close();
ps.close();
// List list = smc.queryForList("AliPayPushScheduleTask.queryList",Maps.newHashMap());
}
public static Date getTimesmorning() {
Calendar cal = Calendar.getInstance();
cal.set(Calendar.HOUR_OF_DAY, 0);
cal.set(Calendar.SECOND, 0);
cal.set(Calendar.MINUTE, 0);
cal.set(Calendar.MILLISECOND, 0);
return cal.getTime();
}
}

posted @ 2018-12-11 09:09  卡卡西sir  阅读(966)  评论(0编辑  收藏  举报