JAVA获取执行sql

import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.mapping.BoundSql;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.mapping.ParameterMapping;
import org.apache.ibatis.mapping.ParameterMode;
import org.apache.ibatis.reflection.MetaObject;
import org.apache.ibatis.reflection.factory.DefaultObjectFactory;
import org.apache.ibatis.reflection.factory.ObjectFactory;
import org.apache.ibatis.reflection.wrapper.DefaultObjectWrapperFactory;
import org.apache.ibatis.reflection.wrapper.ObjectWrapperFactory;
import org.apache.ibatis.session.Configuration;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.TypeHandlerRegistry;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import com.alibaba.fastjson.JSONObject;
public class ExportJobHelper {

@Autowired
private SqlSessionFactory sqlSessionFactory;
private final ObjectFactory DEFAULT_OBJECT_FACTORY = new DefaultObjectFactory();
private final ObjectWrapperFactory DEFAULT_OBJECT_WRAPPER_FACTORY = new DefaultObjectWrapperFactory();

/**
 * 反射对象,增加对低版本Mybatis的支持
 * 
 * @param object
 *            反射对象
 * @return
 */
public MetaObject forObject(Object object) {
    return MetaObject.forObject(object, DEFAULT_OBJECT_FACTORY,
            DEFAULT_OBJECT_WRAPPER_FACTORY);
}

/**
 * 通过命名空间方式获取sql
 * @param namespace statementID
 * @param params 参数
 * @return
 */
public String getNamespaceSql(String namespace, Object params,SqlSession sqlFactory) {
//      ApplicationContext applicationContext= new ClassPathXmlApplicationContext("classpath:spring/spring-mybatis.xml");
//      SqlSessionFactory sqlFactory =(SqlSessionFactory) applicationContext.getBean("systemSqlSessionFactory");

    params = wrapCollection(params);
    Configuration configuration = sqlFactory.getConfiguration();
    MappedStatement mappedStatement = configuration.getMappedStatement(namespace);
    TypeHandlerRegistry typeHandlerRegistry = mappedStatement.getConfiguration().getTypeHandlerRegistry();
    BoundSql boundSql = mappedStatement.getBoundSql(params);
    List<ParameterMapping> parameterMappings = boundSql.getParameterMappings();
    String sql = boundSql.getSql();
    if (parameterMappings != null) {
        for (int i = 0; i < parameterMappings.size(); i++) {
            ParameterMapping parameterMapping = parameterMappings.get(i);
            if (parameterMapping.getMode() != ParameterMode.OUT) {
                Object value;
                String propertyName = parameterMapping.getProperty();
                if (boundSql.hasAdditionalParameter(propertyName)) {
                    value = boundSql.getAdditionalParameter(propertyName);
                } else if (params == null) {
                    value = null;
                } else if (typeHandlerRegistry.hasTypeHandler(params.getClass())) {
                    value = params;
                } else {
                    MetaObject metaObject = configuration.newMetaObject(params);
                    value = metaObject.getValue(propertyName);
                }
                JdbcType jdbcType = parameterMapping.getJdbcType();
                if (value == null && jdbcType == null)
                    jdbcType = JdbcType.NULL;
                    //jdbcType = configuration.getJdbcTypeForNull();

                sql = replaceParameter(sql, value, jdbcType,parameterMapping.getJavaType());
            }
        }
    }
    return sql;
}



/**
 * 根据类型替换参数 仅作为数字和字符串两种类型进行处理,需要特殊处理的可以继续完善这里
 * 
 * @param sql
 * @param value
 * @param jdbcType
 * @param javaType
 * @return
 */
private String replaceParameter(String sql, Object value,
        JdbcType jdbcType, Class javaType) {
    String strValue = String.valueOf(value);
    if (jdbcType != null) {
        switch (jdbcType) {
        // 数字

        case BIT:
        case TINYINT:
        case SMALLINT:
        case INTEGER:
        case BIGINT:
        case FLOAT:
        case REAL:
        case DOUBLE:
        case NUMERIC:
        case DECIMAL:
            break;
        // 日期

        case DATE:
        case TIME:
        case TIMESTAMP:
            // 其他,包含字符串和其他特殊类型

        default:
            strValue = "'" + strValue + "'";

        }
    } else if (Number.class.isAssignableFrom(value.getClass())) {
        // 不加单引号

    } else {
        strValue = "'" + strValue + "'";
    }
    return sql.replaceFirst("\\?", strValue);
}

/**
 * 获取指定的方法
 * 
 * @param clazz
 * @param methodName
 * @return
 */
private Method getDeclaredMethods(Class clazz, String methodName) {
    Method[] methods = clazz.getDeclaredMethods();
    for (Method method : methods) {
        if (method.getName().equals(methodName)) {
            return method;
        }
    }
    throw new IllegalArgumentException("方法" + methodName + "不存在!");
}

/**
 * 获取参数注解名
 * 
 * @param method
 * @param i
 * @param paramName
 * @return
 */
private String getParamNameFromAnnotation(Method method, int i,
        String paramName) {
    final Object[] paramAnnos = method.getParameterAnnotations()[i];
    for (Object paramAnno : paramAnnos) {
        if (paramAnno instanceof Param) {
            paramName = ((Param) paramAnno).value();
        }
    }
    return paramName;
}

/**
 * 简单包装参数
 * 
 * @param object
 * @return
 */
private Object wrapCollection(final Object object) {
    if (object instanceof List) {
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("list", object);
        return map;
    } else if (object != null && object.getClass().isArray()) {
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("array", object);
        return map;
    }
    return object;
}

public void setSqlSessionFactory(SqlSessionFactory sqlSessionFactory) {
    this.sqlSessionFactory = sqlSessionFactory;
}

}

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值