mybatis(2)

------------恢复内容开始------------

一,连接池

连接池就是用于存储连接的一个容器,容器其实就是一个集合对象,

该集合是线程安全的,不能两个线程拿到统一连接。

该集合还必须实现队列的特性,先进先出

二,mybatis中的连接池

1,3种配置dataSource标签,type采用何种连接池方式,type属性取值:

  1.1POOLED  采用传统的javax.sql.DataSource规范种的连接池,mybatis中有针对这种规范的实现

  1.2UNPOOLED  采用传统获取连接的方式,虽然实现了javax.sql.DataSource接口,但是,每一次连接都创建一次对象,并释放

  1.3JNDI  采用服务器提供的JNDI技术实现,来获取dataSource对象,不同的服务器拿到的对象不同,

注意:不是we'b或者maven的war工程是不能使用的。tomcat采用的连接池是dbcp

三,事务

1,什么是事务

2,事务的四大特性:ACID

3,不考虑隔离性会产生的3个问题

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

5,mybatis中的事务

  1,SqlSession中的commit和rollback

  2,自动提交事务,sqlSessionFactory.openSession(true)

 四,动态SQL

1, if标签

<select id="findByCondation" resultType="User">
                select * from user where 1=1
                <if test="name !=null ">
                and    name=#{name}
                </if>
                <if test="id !=null">
                and id=#{id}
                </if>
        </select>

 2,where

<select id="findByCondation" resultType="User">
                select * from user 
                <if test="name !=null ">
                and    name=#{name}
                </if>
                <if test="id !=null">
                and id=#{id}
                </if>
        </select>

 3,foreach

<!-- foreach 集合查询,动态生成id集合 -->
    <select id="findByRange" resultType="User" >
     select * from user
     <where>
         <if test="idList !=null and idList.size>0">
             <foreach collection="idList" open="and id in (" close=")" item="id" separator=",">
             #{id}
             <!-- 这里的id要于item中的id对应 -->
             </foreach>
         </if>
         
     </where>
    </select>
collection=可迭代的变量
open="开始的语句" item="循环的内容,变量"
separator="循环变量的分割符"
  #{id}:循环的变量

对应的测试:

注意:user中有一个字段idList字段,存放id集合.

//foreach测试
    @Test
    public void testFindByRange() {
        List<Integer> idsIntegers= new ArrayList<Integer>();
        idsIntegers.add(2);
        idsIntegers.add(3);
        User user=new User();
        user.setIdList(idsIntegers);
        //执行保存方法
    List<User>    users=ObjSql.findByRange(user);
        for(User u:users) {
            System.out.println(u);
        }
    }

 4,抽取重复的SQL语句

//定义抽取的SQL
<sql id="defaultUser">
   select * from user
</sql>

//使用抽取的SQL
    <select >
 <include refid="defaultUser">
</select>
原文地址:https://www.cnblogs.com/gjx1212/p/14689593.html