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();
}
}
网友评论