SpringBoot通过反射使用mybatis的Dao操作

需求如下:
SpringBoot通过反射使用mybatis的Dao操作_第1张图片
目的要把所有的Dao和Model封装在一个反射操作的Model里统一管理,在反射过程中方法invoke需要接口的实例,我们都知道接口是不能被实例化的,而java的动态代理可以解决这一问题,有关动态代理的事情本文就不说明了,请自行百度。
代码中我是以反射操作的Model的List作为参数的:

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.List;
import org.apache.ibatis.session.SqlSession;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.influxdb.InfluxDBTemplate;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import com.nbst.idevcloud.dispose.model.CacheModel;

@Component
public class TransactionUtil {

    private static final Logger LOG = LoggerFactory.getLogger(TransactionUtil.class);

    //自动注入SqlSession
    @Autowired
    private SqlSession sqlSession;

    @Autowired
    private InfluxDBTemplate influxDBTemplate;

    @Transactional
    public void mysqlInsertTransaction(List list) throws InstantiationException, IllegalAccessException {
        CacheModel cacheModel = new CacheModel();
        Class ModelClass = null;
        Class DaoClass = null;
        Method m = null;
        for (int i = 0; i < list.size(); i++) {
            cacheModel = (CacheModel) list.get(i);
            try {
                //反射获取model类
                ModelClass = Class.forName(cacheModel.getModelClass());
                //反射获取dao类
                DaoClass = Class.forName(cacheModel.getDaoClass());
                //反射获取dao类中相关操作的方法
                m = DaoClass.getMethod(cacheModel.getMethod(), ModelClass);
                m.invoke(sqlSession.getMapper(DaoClass), cacheModel.getModelValue());
            } catch (ClassNotFoundException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (NoSuchMethodException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (SecurityException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (IllegalArgumentException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (InvocationTargetException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        //实例置空回收
        cacheModel = null;
        ModelClass = null;
        DaoClass = null;
        m = null;
    }
}

你可能感兴趣的:(web项目,springboot)