欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

MyBatis核心SqlSessionFactory的创建

程序员文章站 2022-07-15 11:00:29
...

SqlSessionFactory是每个MyBatis应用的核心

 

其实现方式有两种,使用配置文件或使用JAVA编码。

 

1.配置文件实现

<?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="development">
		<environment id="development">
			<transactionManager type="JDBC" />
			<dataSource type="POOLED">
				<property name="driver" value="${driver}" />
				<property name="url" value="${url}" />
				<property name="username" value="${username}" />
				<property name="password" value="${password}" />
			</dataSource>
		</environment>
	</environments>
	
	<mappers>
		<mapper resource="org/mybatis/example/BlogMapper.xml" />
	</mappers>
	
</configuration> 

 使用时利用下面代码进行初始化

String resource = "org/mybatis/example/Configuration.xml"; 
Reader reader = Resources.getResourceAsReader(resource); 
SqlSessionFactory sqlMapper = new SqlSessionFactoryBuilder().build(reader);
 

2.使用编码实现

DataSource dataSource = new PooledDataSource("com.mysql.jdbc.Driver",
                        "jdbc:mysql://localhost/mybatis?userUnicode=true&amp;characterEncoding=utf8", "admin", "123456");
        Environment environment = new Environment("test", new JdbcTransactionFactory(), dataSource);
        Configuration configuration = new Configuration(environment);
        configuration.addMapper(TestDao.class);
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(configuration);

 

 

生命同期问题

SqlSessionFactoryBuilder 是用过即丢,其生命周期只存在于方法体内

SqlSessionFactory 单例,存在于整合应用运行时