Mybatis创建连接SqlSessionFactory使用
Mybatis 使用
以前使用数据库都是使用springboot 集成的mybatis比较简单开发比较迅速。在上次开发flink对接mybaits时,再想使用springboot集成的mybatis对mapper文件进行注入时,程序就会报错。因为flink是集群部署,那么再使用flink处理数据时,flink时集群分布将数据跑在不同的服务器上。如果使用springboot单例的模式,那么flink在执行数据计算时需要将所有全局单例加载一边,这样是很耗费资源的。所以在flink程序里是不支持全局单例的,那么就需要动态加载链接数据库。所以必须要使用最基础的mybatis的链接方式。
Mybatis 使用流程
代码实现
- mybaits.xml 配置
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<environments default="[环境ID]">
<environment id="【与环境ID一致】">
<transactionManager type="JDBC" />
<dataSource type="POOLED">//mybatis 自带的类型
<property name="driver" value="com.mysql.cj.jdbc.Driver" /> //数据库驱动类
<property name="url" value="数据库连接" />//
<property name="username" value="数据库名称" />
<property name="password" value="数据库密码" />
</dataSource>
</environment>
</environments>
<mappers>
<mapper resource="mapper/studentMapper.xml" />
</mappers>
</configuration>
- 代码实现
private MybatisSessionFactory(Properties dataSourceProperties) {
try (
//读取mybaits 文件
InputStream inputStream = Resources.getResourceAsStream(MYBATIS_CONFIG_NAME)) {
//构建 sqlSessionFactory
tSqlSessionFactory =
new SqlSessionFactoryBuilder().build(inputStream, ENV, dataSourceProperties);
} catch (IOException ioe) {
log.error("sqlSessionFactoryBuilder error ",ioe);
}
log.info("MybatisSqlSessionSingleton inited");
}
public void testConnect() {
try{
SqlSession openSession = tSqlSessionFactory.openSession(autoCommit);
StudentMapper studentMapper= openSession.getMapper(StudentMapper.class);
} catch (Exception e) {
log.info("获取数据库连接失败",e);
return null;
}
}