Mybatis的连接池与事务控制及多表查询
Mybatis的连接池
1.连接池:就是用于存储链接的一个容器,容器其实就是一个集合对象,该集合必须是线程安全的,不能两个线程拿到同一连接。该集合还必须实现队列的特性:先进先出。
实际开发中,都会使用连接池。
它可以减少我们获取连接所消耗的时间。
2。mybatis中的连接池:
提供了三种方式的配置:
配置的位置:主配置文件SqlMapConfig.xml中的dataSource标签,type属性就是表示何种连接池方式。
type属性取值:
POOLED:采用传统的javax.sql.DataSource规范中的连接池,mybatis中有针对规范的实现。
UNPOOLED:采用传统的获取连接的方式,虽然也实现了javax.sql.DataSource接口,但是并没使用池的思想。
JNDI:采用服务器提供的JNDI技术实现,来获取DataSource对象,不同的服务器所能拿到的DataSource是不一样的的。注意:如果不是Web或者maven的war工程是不能使用的。所使用的是tomcat服务器,采用的连接池就是dbcp连接池。
下两张图分别是POOLED和UNP{
POOLED:(从池中获取一个连接来用)
UNPOOLED:(每次创建一个新的连接来用)
Mybatis的事务控制及设计方法
事务是什么?
事务的四大特性:ACID
不考虑隔离性会产生的3个问题
解决办法:四种隔离级别
通过sqlsession对象的commit方法和rollback方法实现事务的提交和回滚。
Mybatis映射文件的SQL深入
1.< if >标签:添加判断条件。利用其中test属性进行判断。
<select id="findUserByCondition" parameterType="user" resultType="user">
select * from user where 1=1
<if test="username != null">
and username = #{
username}
</if>
<if test="sex != null">
and sex = #{
sex}
</if>
</select>
2.< where >标签:避免在sql语句中添加where判断。
select * from user
<where>
<if test="username != null">
and username = #{
username}
</if>
<if test="sex != null">
and sex = #{
sex}
</if>
</where>
3.< foreach >标签:拼接
<select id="findUserInIds" resultType="user" parameterType="user">
select * from user
<where>
<if test="ids != null and ids.size()>0">
<foreach collection="ids" open="and id in (" close=")" item="id" separator=",">
#{
id}
</foreach>
</if>
</where>
</select>
4.< sql > 标签:抽取重复的sql语句。
<sql id="defaultUser">
select * from user;
</sql>
即可在所需要该语句的地方用< include >标签进行使用。
<include refid="defaultUser"></include>