Mybatis中的连接池
- mybatis连接池提供了3种方式的配置:
- 配置的位置:
主配置文件SqlMapConfig.xml中的dataSource标签,type属性就是表示采用何种连接池方式。- type属性的取值:
- POOLED 采用传统的javax.sql.DataSource规范中的连接池,mybatis中有针对规范的实现
- UNPOOLED 采用传统的获取连接的方式,虽然也实现Javax.sql.DataSource接口,但是并没有使用池的思想。
- JNDI 采用服务器提供的JNDI技术实现,来获取DataSource对象,不同的服务器所能拿到DataSource是不一样。
注意:如果不是web或者maven的war工程,是不能使用的。
- 配置的位置:
mybatis中的事务
session = new SqlSessionFactoryBuilder().build(in).openSession(true);
通过向openSession方法中传true可以开启事务的自动提交
注意:只有在一个事务只有一条SQL语句时才这么用.
多条SQL语句时,通过sqlsession对象的commit方法和rollback方法实现事务的提交和回滚
mybatis中的动态SQL
动态SQL主要就是对<if> <where> <foreach>
三种标签的使用
通过示例来学习
- 示例1
<!--通过某些信息查询User-->
<select id="findUserByCondition" resultType="user" parameterType="user">
select * from user
<where>
<if test="name != null">
and username = #{name}
</if>
<if test="sex != null">
and sex = #{sex}
</if>
</where>
</select>
通过以上代码拼接出的SQL语句为
select * from user where name="?" and sex="?"
可以看出<where>
标签用于自动拼接SQL语句中的where
<if>
标签用于拼接具体的条件
- 示例2
<!-- 查询在 id 的范围之中的用户 -->
<select id="findInIds" resultType="user" parameterType="queryvo">
<!-- 拼接出select * from user where id in (1,2,3,4,5); -->
select * from user
<where>
<if test="ids != null and ids.size() > 0">
<foreach collection="ids" open="id in ( " close=")" item="uid" separator=",">
#{uid} <!--要与属性列表中的item对应-->
</foreach>
</if>
</where>
</select>
通过以上代码拼接出的SQL语句为
select * from user where id in (1,2,3,4,5)
<foreach>
标签中的collection代表要遍历的目标