mybatis的连接池&事务
一:连接池:数据库连接池负责分配,管理,释放数据库连接
- 实际开发中一般都会使用连接池,可以减少获取连接所消耗的时间
- Mybatis 中数据源的配置
我们的数据源配置就是在 SqlMapConfig.xml 文件中
<!-- 配置数据源(连接池)信息 -->
<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>
三种连接池
MyBatis 在初始化时,根据<dataSource>的 type 属性来创建相应类型的的数据源 DataSource,即:
type=”POOLED”:MyBatis 会创建 PooledDataSource 实例
type=”UNPOOLED” : MyBatis 会创建 UnpooledDataSource 实例
type=”JNDI”:MyBatis 会从 JNDI 服务上查找 DataSource 实例,然后返回使用
- 具体源码分析 省略
二: Mybatis 的事务控制
-
在 JDBC 中我们可以通过手动方式将事务的提交改为手动方式,通过setAutoCommit()方法就可以调整。那么我们的 Mybatis 框架因为是对 JDBC 的封装,所以 Mybatis 框架的事务控制方式,本身也是用 JDBC 的
setAutoCommit()方法来设置事务提交方式的。
-
Mybatis 中事务提交方式
-
通过分析我们能够发现之前的 CUD 操作过程中,我们都要手动进
行事务的提交,原因是 setAutoCommit()方法,在执行时它的值被设置为 false 了,所以我们在 CUD 操作中, 必须通过 sqlSession.commit()(设置**factory.openSession(true);即为自动提交)。
-
-
Mybatis 的动态 SQL 语句
- 动态 SQL 之标签
持久层的Dao映射配置 <select id="findByUser" resultType="user" parameterType="user"> select * from user where 1=1 <if test="username!=null and username != '' "> and username like #{username} </if> <if test="address != null"> and address like #{address} </if> </select>
- 动态 SQL 之标签
<!-- 查询所有用户在 id 的集合之中 --> <select id="findInIds" resultType="user" parameterType="queryvo"> <!-- select * from user where id in (1,2,3,4,5); --> <include refid="defaultSql"></include> <where> <if test="ids != null and ids.size() > 0"> <foreach collection="ids" open="id in ( " close=")" item="uid" separator=","> #{uid} </foreach> </if> </where> </select> SQL 语句: select 字段 from user where id in (?) <foreach>标签用于遍历集合,它的属性: collection:代表要遍历的集合元素,注意编写时不要写#{} open:代表语句的开始部分 close:代表结束部分 item:代表遍历集合的每个元素,生成的变量名 sperator:代表分隔符