sqlSessionFactoryBuider
它是利用xml或java编码获得资源构建SqlSessionFactory
,可构建多个SqlSessionFactory,只负责构建,是一个构建器。一般应用在局部,用完,就回收。
sqlSessionFactory
它的作用是创建SqlSession,而SqlSession就是一个回话,相当于JDBC的Connection对象。
每创建一个sqlSessionFactory,就打开数据库连接资源,故一般一个数据库创建一个SqlSession,这样避免过多Connection消耗。
sqlSession
相当于Connection,它的生命周期存在于请求数据库处理事务过程中。每次用完就要关闭,否则让它长期存在就会使得数据库连接池活动资源减少,对性能影响很大。
注:它是一个线程不安全的对象,在涉及多线程的时候,我们操作数据库需要注意其隔离级别,数据库锁等高级特性。
mybatis 配置xml文件引入映射器方式:
方式一:用文件路径引入
<mappers>
<mapper resource="com/fc/mapper/roleMapper.xml"/>
</mappers>
方式二:用类注册引入
<mappers>
<mapper class="com.fc.mapper.RoleMapper.xml"/>
</mappers>
方式二:用包名引入
<mappers>
<package name="com.fc.mapper"/>
</mappers>
级联:
association,代表一对一
collection,代表一对多
discriminator,是鉴别器,它可以根据实际选择用哪个类作为实例。比如,人有男人女人。
association:
表:
实体类:
mapping.xml
一对一:
<!-- 一对一 方式一:-->
<resultMap type="_Classes" id="ClassOfResultMap">
<id property="id" column="c_id"/>
<result property="name" column="c_name"/>
<!-- 用于一对一 -->
<association property="teacher" javaType="_Teacher">
<id property="tId" column="t_id" />
<result property="tName" column="t_name" />
</association>
</resultMap>
<!-- 例子 -->
<select id="selectOfClass" parameterType="int" resultMap="ClassOfResultMap">
select * from class a,teacher b where a.teacher_id=b.t_id
</select>
一对多
<!-- 一对多 方式一 -->
<resultMap type="_Classes" id="StudentOfResultMap">
<id property="id" column="c_id"/>
<result property="name" column="c_name"/>
<!-- 由于一对多 -->
<collection property="students" ofType="_Student">
<id property="id" column="s_id"/>
<result property="name" column="s_name"/>
</collection>
</resultMap>
<!-- 例子 -->
<select id="selectOfStudent" parameterType="int" resultMap="StudentOfResultMap">
select * from class a,student b where a.c_id=b.class_id and class_id = #{students}
</select>