Mybatis中是连接池事务以及动态sql

一、Mybatis中的连接池

      1.Mybatis连接池提供三种

          配置位置:主配置文件中的dataSource标签,type属性就是表示采用何种连接池方式:

              tpye属性值:

                     POOLED:采用传统的javax.sql.DataSource规范中的连接池,

                     UNPOOLED:不使用连接池

                     JNDI: 采用服务器提供的JNDI技术实现,来获取DataSurce对象(如果不是web或者Maven的war工程不能使用)

                     JNDI使用:

                              1)创建一个web工程

                               2)在webapp下创建一个META-INF目录

                               3)在META-INF目录下创建context.xml文件配置连接信息 :                             

<Context>
<Resource 
name="jdbc/mybatis"                        数据源的名称
type="javax.sql.DataSource"                        数据源类型
auth="Container"                                数据源提供者
maxActive="20"                                    最大活动数
maxWait="10000"                                    最大等待时间
maxIdle="5"                                        最大空闲数
username="root"                                    用户名
password="123"                                    密码
driverClassName="com.mysql.jdbc.Driver"            驱动类
url="jdbc:mysql://localhost:3306/mabse"    连接url字符串
/>
</Context>

                             4)修改SqlMapConfig.xml文件中的连接池信息和连接数据库的信息                                  

<!-- 配置连接数据库的必备信息  type属性表示是否使用数据源(连接池)
value的值:
java:comp/env/后面跟配置信息中的name
-->
            <dataSource type="JNDI">
                <property name="data_source" value="java:comp/env/jdbc/mybatis"/>
            </dataSource>

 

 

二、Mybatis中的事务

         1.什么是事务?

         2.事务的四大特性

         3.不考虑隔离级别产生三大问题

         4.解决办法:四种隔离级别

   请看:https://www.cnblogs.com/cqyp/p/12432815.html 

         Mybatis中通过SqlSession对象的commit方法和rollback方法实现事务的提交回滚

         实现自动提交:

                       session = factory.openSession(true); 

三、动态sql

      根据例子来熟悉动态sql的标签

     1.例:<if>         

   

   <sql id="defaultUSer">
       select * from user
   </sql> 

    <!--  根据传入的参数条件查询
      查询条件:可能为姓名、性别、地址,也可都没有-->
<select id="findUserByCondition" resultType="user" parameterType="user">
   <include refid="defaultUser"></include>
    <where>
<!--
suffixOverrides: 
-->
     <trim suffixOverrides="AND">
        <if test="username!=null">
            and username=#{username}
        </if>
        <if test="sex!=null">
            and sex=#{sex}
        </if>
     </trim>

    </where>
</select>

 

 

  2.例:<foreach>

<!--    根据queryvo中提供的id集合,查询用户信息-->
    <select id="findUserInIds" resultType="user" parameterType="user">
        select * from user
        <where>
            <if test="ids!=null and ids.size()>0">
      <!-- collection: 要遍历的集合,
           open: 以什么开始,前缀
           close: 以什么结束,后缀
           item: 可随意填,但要和#{值一致} ,表示在迭代过程中每一个元素的别名    
      -->

                <foreach collection="ids" open="and id in (" close=")" item="id" separator=",">
                    #{id}
                </foreach>
            </if>
        </where>
    </select>

 

 

 

        

posted @ 2020-03-14 14:29  撑起一片阳光  阅读(279)  评论(0编辑  收藏  举报