美文网首页
运行时动态生成mybatis dao对象

运行时动态生成mybatis dao对象

作者: TinyThing | 来源:发表于2020-04-24 17:13 被阅读0次

代码如下

@Component
public class MybatisUtils implements ApplicationContextAware {

    private static SqlSessionTemplate sqlSessionTemplate;
    private static final ResourcePatternResolver resourceResolver = new PathMatchingResourcePatternResolver();

    private static final String DEFAULT_LOCATION = "classpath:mapper/**/*.xml";

    private static final Map<Class<?>, Object> CACHE = new HashMap<>();

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        sqlSessionTemplate = applicationContext.getBean(SqlSessionTemplate.class);
    }


    @SuppressWarnings("unchecked")
    public static <T> T getMapper(Class<T> mapperClass, String xmlPath) {

        Object mapper = CACHE.get(mapperClass);

        if (mapper != null) {
            return (T) mapper;
        }

        if (StringUtils.isEmpty(xmlPath)) {
            xmlPath = DEFAULT_LOCATION;
        }

        synchronized (CACHE) {
            mapper = CACHE.get(mapperClass);
            if (mapper != null) {
                return (T) mapper;
            }

            try {
                addXmlMappers(xmlPath);
            } catch (IOException e) {
                throw new RuntimeException("parse xml mapper error!");
            }

            mapper = sqlSessionTemplate.getMapper(mapperClass);
            CACHE.put(mapperClass, mapper);
        }


        return (T) mapper;
    }


    private static void addXmlMappers(String location) throws IOException {
        Resource[] resources = getResources(location);
        Configuration configuration = sqlSessionTemplate.getConfiguration();
        for (Resource resource : resources) {
            XMLMapperBuilder xmlMapperBuilder = new XMLMapperBuilder(resource.getInputStream(),
                                                                     configuration,
                                                                     resource.toString(),
                                                                     configuration.getSqlFragments());
            xmlMapperBuilder.parse();
        }

    }


    private static Resource[] getResources(String location) {
        try {
            return resourceResolver.getResources(location);
        } catch (IOException e) {
            return new Resource[0];
        }
    }

}

相关文章

网友评论

      本文标题:运行时动态生成mybatis dao对象

      本文链接:https://www.haomeiwen.com/subject/exzfwhtx.html