美文网首页
springboot 打jar包 mybatis的别名失效

springboot 打jar包 mybatis的别名失效

作者: 新手党 | 来源:发表于2020-08-18 11:15 被阅读0次

1、mybatis默认使用VFS,所以要自己重写改方法,如下


package com.jingbo.houtai.config;

import org.apache.ibatis.io.VFS;

import org.springframework.core.io.Resource;

import org.springframework.core.io.support.PathMatchingResourcePatternResolver;

import org.springframework.core.io.support.ResourcePatternResolver;

import java.io.IOException;

import java.net.URI;

import java.net.URL;

import java.util.ArrayList;

import java.util.Arrays;

import java.util.List;

/**

* Spring Boot集成MyBatis打包成jar时,找不到类的问题

* @author liufeng

*/

public class MySpringBootVFSextends VFS {

@Override

    public boolean isValid() {

return true;

    }

@Override

    protected Listlist(URL url, String path)throws IOException {

ClassLoader cl =this.getClass().getClassLoader();

        ResourcePatternResolver resolver =new PathMatchingResourcePatternResolver(cl);

        Resource[] resources = resolver.getResources(path +"/**/*.class");

        List resources1 = Arrays.asList(resources);

        List resourcePaths =new ArrayList();

        for (Resource resource: resources1) {

resourcePaths.add(preserveSubpackageName(resource.getURI(), path));

        }

return resourcePaths;

    }

private static StringpreserveSubpackageName(final URI uri, final String rootPath) {

final String uriStr = uri.toString();

        final int start = uriStr.indexOf(rootPath);

        return uriStr.substring(start, uriStr.length());

    }

}



2、自定义sqlsessionFactory


import org.apache.ibatis.session.SqlSessionFactory;

import org.mybatis.spring.SqlSessionFactoryBean;

import org.springframework.beans.factory.annotation.Qualifier;

import org.springframework.context.annotation.Bean;

import org.springframework.context.annotation.Configuration;

import org.springframework.core.io.support.PathMatchingResourcePatternResolver;

import javax.sql.DataSource;

@Configuration

public class MybatisConfig {

@Bean(name ="sqlSessionFactory")

public SqlSessionFactoryclusterSqlSessionFactory(@Qualifier("dataSource") DataSource dataSource)

throws Exception {

final SqlSessionFactoryBean sessionFactory =new SqlSessionFactoryBean();

        sessionFactory.setDataSource(dataSource);

        sessionFactory.setMapperLocations(

new PathMatchingResourcePatternResolver().getResources("classpath*:mapper/*Mapper.xml"));

        sessionFactory.setTypeAliasesPackage("com.jingbo.houtai.entity");

        sessionFactory.getObject().getConfiguration().setMapUnderscoreToCamelCase(true);

        //MyBatis无法扫描Spring Boot别名的Bug 添加下面这行代码

        sessionFactory.setVfs(MySpringBootVFS.class);

        return sessionFactory.getObject();

    }

}

相关文章

网友评论

      本文标题:springboot 打jar包 mybatis的别名失效

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