MyBatis xml文件动态生成对象,网上找的自己进行了优化。

主要针对动态分页查询,因为日常中查询,可以利用其实现动态分页操作,实现所有的select都能够动态生成以此基础。

{******************************方法应用******************************************************************************************************

org.apache.ibatis.session.Configuration config = new Configuration();

String mapps="是xml文件读取字符串!";

org.apache.ibatis.session.SqlSessionFactory  sqlSessionFactory = SqlSessionCache.createSqlSessionFactory(config, mapps);

Map params="map参数集合!";

javax.sql.DataSource dataSource=“数据源”;

java.sql.Connection newconn=dataSource.getConnection();

org.apache.ibatis.session.SqlSession session = sqlSessionFactory.openSession(newconn);
session.clearCache();

Class type=MbatisDao.class;

//接口要与xml @DAO_INTERFACE保持一致

//<mapper namespace="@DAO_INTERFACE">
MbatisDao um= session.getMapper(type);

   //findPageTotal 方法在接口和xml,id中要有对应  否则调用报错
   long total = um.findPageTotal(params);

session.close();

******************************方法应用******************************************************************************************************}

参考:http://www.360doc.com/content/15/0124/23/281812_443454253.shtml

package com.*****.service.sys.jdbcApi.impl;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import org.apache.ibatis.builder.xml.XMLMapperBuilder;
import org.apache.ibatis.parsing.XNode;
import org.apache.ibatis.session.Configuration;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.apache.log4j.Logger;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;

public class SqlSessionCache {
 private static Logger log = Logger.getLogger(SqlSessionCache.class);
 private SqlSessionFactory sqlSessionFactory;
 private Resource[] mapperLocations;
 private String packageSearchPath;
 private HashMap<String, Long> fileMapping = new HashMap<String, Long>();// 记录文件是否变化

 public void refreshMapper() {
  try {
   Configuration configuration =null;
   if(this.sqlSessionFactory!=null){
    configuration = this.sqlSessionFactory.getConfiguration();
   }
   // step.1 扫描文件
   try {
    this.scanMapperXml();
   } catch (IOException e) {
    log.error("packageSearchPath扫描包路径配置错误");
    return;
   }

   log.debug("==============刷新前mapper中的内容===============");
   if(configuration!=null){
    for (String name : configuration.getMappedStatementNames()) {
     System.out.println(name);
    }
   }
   // step.2 判断是否有文件发生了变化
   if (this.isChanged()) {
    // step.2.1 清理
    this.removeConfig(configuration);

    // step.2.2 重新加载
    for (Resource configLocation : mapperLocations) {
     try {
      Map<String, XNode> sqlFragments =configuration.getSqlFragments();
      XMLMapperBuilder xmlMapperBuilder = new XMLMapperBuilder(
        configLocation.getInputStream(), //内存级动态SQL实现就是将该流实现动态加载
        configuration,//将configuration 就是通过XMLMapperBuilder完善所有项  使用特性引用传值
        configLocation.toString(),//就是为了配置键值对存在的,可以试试路径方式实现
        sqlFragments);
      xmlMapperBuilder.parse();
      log.debug("mapper文件[" + configLocation.getFilename()+ "]缓存加载成功");
     } catch (IOException e) {
      log.error("mapper文件[" + configLocation.getFilename()+ "]不存在或内容格式不对");
      continue;
     }catch (Exception e) {
      e.printStackTrace();
     }
    }
   }

   log.debug("==============刷新后mapper中的内容===============");
   if(configuration!=null){
    for (String name : configuration.getMappedStatementNames()) {
     System.out.println(name);
    }
   }
  } catch (Exception e) {
   e.printStackTrace();
  }
 }

 public void setPackageSearchPath(String packageSearchPath) {
  this.packageSearchPath = packageSearchPath;
 }

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

 /**
  * 扫描xml文件所在的路径
  *
  * @throws IOException
  */
 private void scanMapperXml() throws IOException {
  this.mapperLocations = new PathMatchingResourcePatternResolver().getResources(packageSearchPath);
 }

 /**
  * 清空Configuration中几个重要的缓存
  *
  * @param configuration
  * @throws Exception
  */
 private static void removeConfig(Configuration configuration) throws Exception {
  if(configuration!=null){
   Class<?> classConfig = configuration.getClass();
   clearMap(classConfig, configuration, "mappedStatements");
   clearMap(classConfig, configuration, "caches");
   clearMap(classConfig, configuration, "resultMaps");
   clearMap(classConfig, configuration, "parameterMaps");
   clearMap(classConfig, configuration, "keyGenerators");
   clearMap(classConfig, configuration, "sqlFragments");
   clearSet(classConfig, configuration, "loadedResources");
  }else{
   configuration=new Configuration();
  }
 }

 @SuppressWarnings("rawtypes")
 private static void clearMap(Class<?> classConfig, Configuration configuration,
   String fieldName) throws Exception {
  Field field = classConfig.getDeclaredField(fieldName);
  field.setAccessible(true);
  Map mapConfig = (Map) field.get(configuration);
  if(mapConfig!=null && mapConfig.size()>0){
   mapConfig.clear();
  }
 }

 @SuppressWarnings("rawtypes")
 private static void clearSet(Class<?> classConfig, Configuration configuration,
   String fieldName) throws Exception {
  Field field = classConfig.getDeclaredField(fieldName);
  field.setAccessible(true);
  Set setConfig = (Set) field.get(configuration);
  if(setConfig!=null && setConfig.size()>0){
   setConfig.clear();
  }
 }

 /**
  * 判断文件是否发生了变化
  *
  * @param resource
  * @return
  * @throws IOException
  */
 private boolean isChanged() throws IOException {
  boolean flag = false;
  for (Resource resource : mapperLocations) {
   String resourceName = resource.getFilename();

   boolean addFlag = !fileMapping.containsKey(resourceName);// 此为新增标识

   // 修改文件:判断文件内容是否有变化
   Long compareFrame = fileMapping.get(resourceName);
   
   long lastFrame = resource.contentLength() + resource.lastModified();
   boolean modifyFlag = null != compareFrame
     && compareFrame.longValue() != lastFrame;// 此为修改标识

   // 新增或是修改时,存储文件
   if (addFlag || modifyFlag) {
    fileMapping.put(resourceName, Long.valueOf(lastFrame));// 文件内容帧值
    flag = true;
   }
  }
  return flag;
 }
 
 /**
  * 封装XMLMapperBuilder动态加载(xml)创建MyBatis SqlSessionFactory
  * @param mapps
  * @return
  */
 public static SqlSessionFactory createSqlSessionFactory(String mapps){
  //第一步:实现文件级动态SQL加载通用底层
  //第二步:实现内存级动态SQL加载通用底层
  //需要重写mybatis相关类
  /** 动态加载就是将一下的这段代码替换   ---stat---------
  SqlSessionCache sc=new SqlSessionCache();
  String pxml="com/*****/service/sys/jdbcApi/impl/MbatisDao.xml";
  sc.setPackageSearchPath(pxml);
  sc.setSqlSessionFactory(sessionMyBatis);
  //重新加载myBatis查询方法
  sc.refreshMapper();
   动态加载就是将一下的这段代码替换     ---end-------- */
  SqlSessionFactory sessionMyBatis=null;
  try{
   log.debug("==============载入xml字符串后  创建Factory,装在XMLMapper===============");
    String pxml="";//com/*****/service/sys/jdbcApi/impl/MbatisDao.xml
    Configuration config=new Configuration();
    InputStream inputStream=new ByteArrayInputStream(mapps.getBytes("UTF-8"));
    sessionMyBatis=new SqlSessionFactoryBuilder().build(config);
    config = sessionMyBatis.getConfiguration();
    removeConfig(config);
    Map<String, XNode> sqlFragments =config.getSqlFragments();
    XMLMapperBuilder xmlMapperBuilder = new XMLMapperBuilder(
      inputStream,//configLocation.getInputStream(), //内存级动态SQL实现就是将该流实现动态加载
      config,//将configuration 就是通过XMLMapperBuilder完善所有项  使用特性引用传值
      pxml,//configLocation.toString(),//就是为了配置键值对存在的,可以试试路径方式实现
      sqlFragments);
    xmlMapperBuilder.parse();
    log.debug("==============载入xml字符串后  mapper中的内容数据【输出开始】===============");
    if(config!=null){
     for (String name : config.getMappedStatementNames()) {
      log.debug("=============>>"+name);
     }
    }
    log.debug("==============载入xml字符串后  mapper中的内容数据【输出结束】===============");
  }catch (Exception ex) {
   ex.printStackTrace();
  }
  return sessionMyBatis;
 }
 /**
  * 封装XMLMapperBuilder动态加载(xml)创建MyBatis SqlSessionFactory
  * @param config
  * @param mapps
  * @return
  */
 public static SqlSessionFactory createSqlSessionFactory(Configuration config,String mapps){
  //第一步:实现文件级动态SQL加载通用底层
  //第二步:实现内存级动态SQL加载通用底层
  //需要重写mybatis相关类
  /** 动态加载就是将一下的这段代码替换   ---stat---------
  SqlSessionCache sc=new SqlSessionCache();
  String pxml="com/*****/service/sys/jdbcApi/impl/MbatisDao.xml";
  sc.setPackageSearchPath(pxml);
  sc.setSqlSessionFactory(sessionMyBatis);
  //重新加载myBatis查询方法
  sc.refreshMapper();
   动态加载就是将一下的这段代码替换     ---end-------- */
  SqlSessionFactory sessionMyBatis=null;
  try{
   log.debug("==============载入xml字符串后  创建Factory,装在XMLMapper===============");
    String pxml="";//com/*****/service/sys/jdbcApi/impl/MbatisDao.xml
    InputStream inputStream=new ByteArrayInputStream(mapps.getBytes("UTF-8"));
    sessionMyBatis=new SqlSessionFactoryBuilder().build(config);
    config = sessionMyBatis.getConfiguration();
    removeConfig(config);
    Map<String, XNode> sqlFragments =config.getSqlFragments();
    XMLMapperBuilder xmlMapperBuilder = new XMLMapperBuilder(
      inputStream,//configLocation.getInputStream(), //内存级动态SQL实现就是将该流实现动态加载
      config,//将configuration 就是通过XMLMapperBuilder完善所有项  使用特性引用传值
      pxml,//configLocation.toString(),//就是为了配置键值对存在的,可以试试路径方式实现
      sqlFragments);
    xmlMapperBuilder.parse();
    log.debug("==============载入xml字符串后  mapper中的内容数据【输出开始】===============");
    if(config!=null){
     for (String name : config.getMappedStatementNames()) {
      log.debug("=============>>"+name);
     }
    }
    log.debug("==============载入xml字符串后  mapper中的内容数据【输出结束】===============");
  }catch (Exception ex) {
   ex.printStackTrace();
   log.error("XML异常配置:"+mapps);
  }
  return sessionMyBatis;
 }
 /**
  * 封装XMLMapperBuilder动态加载(xml)创建MyBatis SqlSessionFactory
  * @param mapps
  * @return
  */
 public static SqlSessionFactory createSqlSessionFactory(InputStream inputStream){
  SqlSessionFactory sessionMyBatis=null;
  try{
   log.debug("==============载入xml字符串后  创建Factory,装在XMLMapper===============");
    String pxml="";//com/*****/service/sys/jdbcApi/impl/MbatisDao.xml
    Configuration config=new Configuration();
    //InputStream inputStream=new ByteArrayInputStream(mapps.getBytes("UTF-8"));
    sessionMyBatis=new SqlSessionFactoryBuilder().build(config);
    config = sessionMyBatis.getConfiguration();
    removeConfig(config);
    Map<String, XNode> sqlFragments =config.getSqlFragments();
    XMLMapperBuilder xmlMapperBuilder = new XMLMapperBuilder(
      inputStream,//configLocation.getInputStream(), //内存级动态SQL实现就是将该流实现动态加载
      config,//就是将configuration 通过XMLMapperBuilder完善所有项  使用特性引用传值
      pxml,//configLocation.toString(),//就是为了配置键值对存在的,可以试试路径方式实现
      sqlFragments);
    xmlMapperBuilder.parse();
    log.debug("==============载入xml字符串后  mapper中的内容数据【输出开始】===============");
    if(config!=null){
     for (String name : config.getMappedStatementNames()) {
      log.debug("=============>>"+name);
     }
    }
    log.debug("==============载入xml字符串后  mapper中的内容数据【输出结束】===============");
  }catch (Exception ex) {
   ex.printStackTrace();
  }
  return sessionMyBatis;
 }
 
 /**
  * 封装XMLMapperBuilder动态加载(xml)创建MyBatis SqlSessionFactory
  * @param mapps
  * @return
  */
 public static SqlSessionFactory createSqlSessionFactory(Resource configLocation){
  SqlSessionFactory sessionMyBatis=null;
  try{
   log.debug("==============载入xml字符串后  创建Factory,装在XMLMapper===============");
    String pxml="";//com/*****/service/sys/jdbcApi/impl/MbatisDao.xml
    Configuration config=new Configuration();
    //InputStream inputStream=new ByteArrayInputStream(mapps.getBytes("UTF-8"));
    sessionMyBatis=new SqlSessionFactoryBuilder().build(config);
    config = sessionMyBatis.getConfiguration();
    removeConfig(config);
    Map<String, XNode> sqlFragments =config.getSqlFragments();
    XMLMapperBuilder xmlMapperBuilder = new XMLMapperBuilder(
      configLocation.getInputStream(), //内存级动态SQL实现就是将该流实现动态加载
      config,//就是将configuration 通过XMLMapperBuilder完善所有项  使用特性引用传值
      configLocation.toString(),//就是为了配置键值对存在的,可以试试路径方式实现
      sqlFragments);
    xmlMapperBuilder.parse();
    log.debug("==============载入xml字符串后  mapper中的内容数据【输出开始】===============");
    if(config!=null){
     for (String name : config.getMappedStatementNames()) {
      log.debug("=============>>"+name);
     }
    }
    log.debug("==============载入xml字符串后  mapper中的内容数据【输出结束】===============");
  }catch (Exception ex) {
   ex.printStackTrace();
  }
  return sessionMyBatis;
 }
 
 /**
  * 扫描xml文件所在的路径
  * @param packageSearchPath
  * @throws IOException
  */
 public static String scanMapperXml(String packageSearchPath) throws IOException {
  String mappr =null;
  Resource[] mapperLocations = new PathMatchingResourcePatternResolver().getResources(packageSearchPath);
  for (Resource configLocation : mapperLocations) {
   InputStream in = configLocation.getInputStream();
   ByteArrayOutputStream baos = new ByteArrayOutputStream();
         int i=-1;
         while((i=in.read())!=-1){
          baos.write(i);
         }
   mappr = baos.toString();
  }
  return mappr;
 }
 

}




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值