2.Mybatis框架学习笔记之连接池,动态sql

对应工程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连接池。

动态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语句加分号;表示语句结束,如果你要拼接的话,就不要写分号。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值