非SpringBoot项目集成MyBatis-Plus
1. 引入maven依赖
<!-- https://mvnrepository.com/artifact/com.baomidou/mybatis-plus -->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus</artifactId>
<version>3.5.6</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.baomidou/mybatis-plus-extension -->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-extension</artifactId>
<version>3.5.6</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.zaxxer/HikariCP -->
<dependency>
<groupId>com.zaxxer</groupId>
<artifactId>HikariCP</artifactId>
<version>4.0.3</version>
</dependency>
<!-- Mysql驱动包 -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-nop</artifactId>
<version>1.7.2</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.projectlombok/lombok -->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.32</version>
<scope>provided</scope>
</dependency>
2. 编写初始化数据源单例 DataSourceInitializer
private static DataSourceInitializer instance = new DataSourceInitializer();
public static DataSourceInitializer getInstance() {
return instance;
}
private SqlSession session;
private DataSourceInitializer() {
try {
SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();
//这是mybatis-plus的配置对象,对mybatis的Configuration进行增强
MybatisConfiguration configuration = new MybatisConfiguration();
//初始化配置
initConfiguration(configuration);
//这是初始化连接器,如mybatis-plus的分页插件
configuration.addInterceptor(initInterceptor());
//配置日志实现
configuration.setLogImpl(Slf4jImpl.class);
//扫描mapper接口所在包
configuration.addMappers("com.example.mapper");
//构建mybatis-plus需要的globalconfig
GlobalConfig globalConfig = GlobalConfigUtils.getGlobalConfig(configuration);
//此参数会自动生成实现baseMapper的基础方法映射
globalConfig.setSqlInjector(new DefaultSqlInjector());
//设置id生成器
globalConfig.setIdentifierGenerator(new DefaultIdentifierGenerator());
//设置超类mapper
globalConfig.setSuperMapperClass(BaseMapper.class);
//设置数据源
Environment environment = new Environment("1", new JdbcTransactionFactory(), initDataSource());
configuration.setEnvironment(environment);
this.registryMapperXml(configuration, "mapper");
//构建sqlSessionFactory
SqlSessionFactory sqlSessionFactory = builder.build(configuration);
//创建session
this.session = sqlSessionFactory.openSession();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
3. 初始化配置方法
/**
* 初始化配置
*
* @param configuration
*/
private void initConfiguration(MybatisConfiguration configuration) {
//开启驼峰大小写转换
configuration.setMapUnderscoreToCamelCase(true);
//配置添加数据自动返回数据主键
configuration.setUseGeneratedKeys(true);
}
/**
* 初始化数据源
*
* @return
*/
private DataSource initDataSource() {
HikariDataSource dataSource = new HikariDataSource();
dataSource.setJdbcUrl("jdbc:sqlite:db/database.db");
dataSource.setDriverClassName("org.sqlite.JDBC");
dataSource.setIdleTimeout(60000);
dataSource.setAutoCommit(true);
dataSource.setMaximumPoolSize(5);
dataSource.setMinimumIdle(1);
dataSource.setMaxLifetime(60000 * 10);
dataSource.setConnectionTestQuery("SELECT 1");
return dataSource;
}
/**
* 初始化拦截器
*
* @return
*/
private Interceptor initInterceptor() {
//创建mybatis-plus插件对象
MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
//构建分页插件
PaginationInnerInterceptor paginationInnerInterceptor = new PaginationInnerInterceptor();
paginationInnerInterceptor.setDbType(DbType.SQLITE);
paginationInnerInterceptor.setOverflow(true);
paginationInnerInterceptor.setMaxLimit(500L);
interceptor.addInnerInterceptor(paginationInnerInterceptor);
return interceptor;
}
/**
* 解析mapper.xml文件
*
* @param configuration
* @param classPath
* @throws IOException
*/
private void registryMapperXml(MybatisConfiguration configuration, String classPath) throws IOException {
ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader();
Enumeration<URL> mapper = contextClassLoader.getResources(classPath);
while (mapper.hasMoreElements()) {
URL url = mapper.nextElement();
if (url.getProtocol().equals("file")) {
String path = url.getPath();
File file = new File(path);
File[] files = file.listFiles();
for (File f : files) {
FileInputStream in = new FileInputStream(f);
XMLMapperBuilder xmlMapperBuilder = new XMLMapperBuilder(in, configuration, f.getPath(), configuration.getSqlFragments());
xmlMapperBuilder.parse();
in.close();
}
} else {
JarURLConnection urlConnection = (JarURLConnection) url.openConnection();
JarFile jarFile = urlConnection.getJarFile();
Enumeration<JarEntry> entries = jarFile.entries();
while (entries.hasMoreElements()) {
JarEntry jarEntry = entries.nextElement();
if (jarEntry.getName().endsWith(".xml")) {
InputStream in = jarFile.getInputStream(jarEntry);
XMLMapperBuilder xmlMapperBuilder = new XMLMapperBuilder(in, configuration, jarEntry.getName(), configuration.getSqlFragments());
xmlMapperBuilder.parse();
in.close();
}
}
}
}
}
xml文件放在 resources/mapper 下面
4. 其他方法
/**
* 获取mapper类
* @param type
* @return
* @param <T>
*/
public <T> T getMapper(Class<T> type) {
return this.session.getMapper(type);
}
/**
* 销毁数据库连接
*/
public void destroy() {
this.session.commit();
this.session.close();
}
5. 调用Mapper
UserMapper mapper = DataSourceInitializer.getInstance().getMapper(UserMapper .class);
List<User> res= mapper.selectList(null);
System.out.println(res);
原文地址:https://blog.csdn.net/guo__hang/article/details/137910439
免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!