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();

}

}

原文地址:https://www.cnblogs.com/kakaxisir/p/10100359.html

时间: 2024-10-12 03:49:59

ibatis实现动态sql处理的相关文章

IBatis.net动态SQL语句

在学习动态SQL语句之前,首先必须对条件查询有一定了解,先来学习如何向IBatis.Net的映射文件里传入参数. 一.条件查询 1.传递单个参数 如根据Id查询: <select id="SelectPersonById" resultMap="Person" parameterClass="Int32" > SELECT * FROM Person WHERE Id = #Id# --这样传入一个参数 </select>

ibatis的动态sql

1.介绍 1 <select id="getUsers" 2 3 parameterClass="user" 4 5 resultMap="get-user-result"> 6 7 select 8 9 id, 10 11 name, 12 13 sex 14 15 from t_user 16 17 <dynamic prepend="WHERE"> 18 19 <isNotEmpty pre

IBatis的动态SQL的写法

Ⅰ .动态SQL的写法 开始 <dynamic 条件成立时前面要加的字符串 prepend ="字符串"> prepend="字符串" 判断条件的对象属性名 property="字符串" 如果是属性关键字是比较条件时,字符串存放要比较的值compareValue="字符串"> 结束 </dynamic> Ⅱ.动态SQL的标签 一元标签 <iterate>标签 共同的属性 prepend

MyBatis 和 ibatis的动态SQL语句配置符号,不兼容大于号、小于号等特殊符号问题 X

TEST 在XML映射SQL的文件中,很多情况下会使用到大于号.小于号等特殊符号,这时候如果不进行控制是无法编译通过的,这时候需要用到<![CDATA[  ]]>符号进行说明,将此类符号不进行解析,其实,这个问题不止在MyBatis上通用,而是它通用于任何XML的文件中使用,比如Hibernate.Wabacus.Spring等等等等配置文件中,只要是XML文件就行,此类问题在以后的工作中,经常使用. 案例代码 <select id="findAllKiaAnalysisByC

iBatis动态SQL标签用法

1.动态SQL片段 通过SQL片段达到代码复用 <!-- 动态条件分页查询 -->         <sql id="sql_count">                 select count(*)         </sql>         <sql id="sql_select">                 select *         </sql>         <sql i

ibatis 动态SQL

直接使用JDBC一个非常普遍的问题就是动态SQL.使用参数值.参数本身和数据列都是动态SQL,通常是非常困难的.典型的解决办法就是用上一堆的IF-ELSE条件语句和一连串的字符串连接.对于这个问题,Ibatis提供了一套标准的相对比较清晰的方法来解决一个问题,这里有个简单的例子: <select id="getUserList" resultMap="user"> select * from user <isGreaterThan prepend=

IBATIS动态SQL

直接使用JDBC一个非常普遍的问题就是动态SQL.使用参数值.参数本身和数据列都是动态SQL,通常是非常困难的.典型的解决办法就是用上一堆的IF-ELSE条件语句和一连串的字符串连接.对于这个问题,Ibatis提供了一套标准的相对比较清晰的方法来解决一个问题,这里有个简单的例子: <select id="getUserList" resultMap="user"> select * from user <dynamic prepend="

ibatis动态sql配置启动时提示:The content of elements must consist of well-formed character data...

ibatis动态sql配置启动时提示:The content of elements must consist of well-formed character data... 2012-07-18 11:21wuming3632171 | 浏览 5114 次 ibatis配置如下,高手帮我看看.<select id="exportRecieveData" parameterClass="java.util.HashMap"resultClass="

MyBatis 动态sql详解

MyBatis的动态sql语句 1.if 条件 2.choose , when 和 otherwise条件 3.where 条件 where条件:1.自动加上where.2.如果where子句以and或者or开头,则自动删除第一个and或者or..所以我们不需要自己加where 4.trim 条件 trim条件和where条件类似但是功能更强大:不仅可以替换掉子句开头的and或者or,还提供了加前缀和后缀的功能. 5.forEach循环 6.set 条件 set条件:自动加上set,自动去除最后