mybatis学习笔记 - SqlSessionFactory的创建

SqlSessionFactory(sql会话工厂)是mybatis中的一个关键对象,每一个mybatis都是围绕SqlSessionFactory进行的; 1、创建SqlSessionFactory的过程:

①定义Configuration对象(包括数据源,事务,mapper文件资源以及影响数据库行为属性设置的settings)  
--> ②由Configuration对象创建一个SqlSessionFactoryBuilder对象
--> ③由SessionFactoryBuilder获得SqlSessionFactory实例
--> ④由SqlSessionFactory实例获得SqlSession实例,操作数据库

2、创建: *方法一: 1)配置文件mybatis-cfg-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>    
            <properties resource="jdbc.properties"></properties>    //加载配置文件
            <environments default="development">

                <!-- 包含事务管理和连接池的配置,即jdbc环境信息 -->
                <environment id="development">  

                    <!--创建事务 -->
                    <transactionManager type="JDBC" /> 

                    <!--创建使用缓存池的数据源-->
                    <dataSource type="POOLED">
                        <property name="driver" value="${jdbc.driver}" />
                        <property name="url" value="${jdbc.url}" />
                        <property name="username" value="${jdbc.username}" />
                        <property name="password" value="${jdbc.password}" />
                    </dataSource>
                </environment>
            </environments>

            <mappers>   <!-- 加入资源-->
                <mapper resource="zh/mybatis/StudentMapper.xml"/>
            </mappers>
        </configuration>

2)代码实现过程:

public class MybatisTest {
            public static void main(String[] args) throws IOException{
                //配置文件名称
                String resource = "mybatis-cfg.xml";

                //通过mybatis包中的Resources对象获取配置文件
                InputStream inputStream = Resources.getResourceAsStream(resource);
                //或 Reader reader = Resources.getResourceAsReader(resource);

                //通过SqlSessionFactoryBuilder创建SqlSessionFactory实例
                SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);

                //获得实例对象session
                //SqlSession实例用来操作数据库,由SqlSessionFactory的实例创建
                SqlSession session = sqlSessionFactory.openSession();

                StudentMapper studentMapper = session.getMapper(StudentMapper.class);
                Student student = studentMapper.selectById(1);
                System.out.println(student.getSname());
            }
        }

*方法二:mybatis,spring整合时创建SqlSessionFactory <在applicationContext.xml中配置>

<!-- 配置sqlSessionFactory -->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
 <!-- 实例化sqlSessionFactory时需要使用先前配置好的数据源以及SQL映射文件 -->
    <property name="dataSource" ref="dataSource" />
        <property name="mapperLocations" value="classpath:com/cc/mappers/*Mapper.xml" />
</bean>
经验分享 程序员 微信小程序 职场和发展