对应工程datasource-and-txmanage,dynamic-sql
mybatis连接池
我们在实际开发中都会使用连接池,因为它可以减少我们获取连接所消耗的时间。连接池就是用于存储连接的一个容器,容器其实就是一个集合对象,该集合必须是线程安全的,不能两个线程拿到统一连接。该集合还必须实现队列的特性:先进先出
mybatis中的连接池:
mybatis连接池提供了3种方式的配置:
- 配置的位置:
- 主配置文件SqlMapConfig.xml中的dataSource标签,type属性就是表示采用何种连接池方式。
- type属性的取值:
- POOLED:采用传统的
javax.sql.DataSource
规范中的连接池,mybatis中有针对规范的实现。 - UNPOOLED:采用传统的获取连接的方式,虽然也实现
Javax.sql.DataSource
接口,但是并没有使用池的思想。 - JNDI:采用服务器提供的JNDI技术实现,来获取DataSource对象,不同的服务器所能拿到DataSource是不一样。注意:如果不是web或者maven的war工程,是不能使用的。学习过程中使用的是tomcat服务器,采用连接池就是dbcp连接池。
- POOLED:采用传统的
动态sql
mybatis核心对sql语句进行灵活操作,通过表达式进行判断,对sql进行灵活拼接、组装。
if标签
<!-- 配置条件查询-->
<select id="findUserByCondition" parameterType="user" resultType="cn.smm.domain.User">
select * from user where 1=1
<if test="username !=null">
and username = #{username}
</if>
<if test="sex !=null">
and sex = #{sex}
</if>
</select>
SQL语句中where 1=1的意义,包含以下两种情境:动态SQL拼接和查询表结构。
where标签
<select id="findUserByCondition" parameterType="user" resultType="cn.smm.domain.User">
select * from user
<where>
<if test="username !=null">
and username = #{username}
</if>
<if test="sex !=null">
and sex = #{sex}
</if>
</where>
</select>
foreach标签
<select id="findUserInIds" parameterType="cn.smm.domain.QueryVo" resultType="cn.smm.domain.User">
select * from user
<where>
<if test="ids != null and ids.size()>0">
<foreach collection="ids" open="and id in (" close=")" item="uid" separator=",">
#{uid}
</foreach>
</if>
</where>
</select>
补充知识
抽取重复代码:
通过抽取select * from user重复代码,在目标中使用
<!-- 抽取重复的代码-->
<sql id="repeat">
select * from user
</sql>
<!-- 配置查询所有-->
<select id="findAll" resultType="uSeR">
<include refid="repeat"></include>
</select>
SQL语句加分号;
表示语句结束,如果你要拼接的话,就不要写分号。