0
点赞
收藏
分享

微信扫一扫

F004MyBatis学习笔记-MyBatis连接池和动态SQL语句


一、连接池

1、连接池

连接池是用于存储连接的容器;

容器就是一个集合对象,该集合必须是线程安全的,不能两个线程拿到同一连接;

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

 

2、MyBatis连接池

MyBatis连接池提供三种方式配置:

配置的位置:

主配置文件SqlMapConfig.xml文件中的dataSource标签,type表示采用何种连接池方式;

type属性的取值:

POOLED:采用传统的javax.sql.DataSource规范中的连接池,MyBatis中有针对其的规范;

从池中获取连接;

UNPOOLED:采用传统的获取连接的方式,虽然也实现了javax.sql.DataSource接口,但没有使用池的思想;

每次创建连接;

JNDI:采用服务器提供的JNDI技术实现,不同服务器拿到的DataSource是不一样的

JNDI注意:如果不是web或者maven的war工程是不能使用的;tomcat服务器,采用的连接池是dbcp连接池;

 

二、MyBatis动态SQL语句

1、if

接口代码:

//通过条件查询,条件是不固定的,也许是用户名也许是地址等等
List<User> findByCondition(User user);

XML文件代码:

<!--根据条件查询-->
<select id="findByCondition" parameterType="com.zibo.mybatis_crud.domain.User" resultType="com.zibo.mybatis_crud.domain.User">
select * from user where 1=1
<if test="username!=null and username != '' ">
and username like #{username}
</if>
<if test="address != null">
and address like #{address}
</if>
</select>

测试代码:

@Test
public void testFindByCondition(){
//构建一条数据
User user = new User();
user.setUsername("%哥%");
user.setAddress("%周口%");
//5、使用代理对象执行方法
List<User> users = iUserDao.findByCondition(user);
System.out.println(users.size());
for (User user0 : users) {
System.out.println(user0);
}
}

2、where

仅修改XML文件代码为:

<!--根据条件查询-->
<select id="findByCondition" parameterType="com.zibo.mybatis_crud.domain.User" resultType="com.zibo.mybatis_crud.domain.User">
select * from user
<where>
<if test="username!=null and username != '' ">
and username like #{username}
</if>
<if test="address != null">
and address like #{address}
</if>
</where>
</select>

3、foreach和sql标签

接口代码:

//通过条件查询
List<User> findByQueryVo(QueryVo queryVo);

xml文件代码:

<!--根据条件查询-->
<select id="findByQueryVo" parameterType="com.zibo.mybatis_crud.domain.QueryVo" resultType="com.zibo.mybatis_crud.domain.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>

测试代码:

@Test
public void testFindByQueryVo(){
//构建一条数据
QueryVo queryVo = new QueryVo();
List<Integer> list = new ArrayList<>();
list.add(42);
list.add(45);
list.add(48);
list.add(49);
queryVo.setIds(list);
//5、使用代理对象执行方法
List<User> users = iUserDao.findByQueryVo(queryVo);
for (User user0 : users) {
System.out.println(user0);
}
}

抽取重复sql代码(了解):

<!--    抽取重复sql语句-->
<sql id="defaultSQL">
select * from user;
</sql>
<!--配置查询所有-->
<select id="findAll" resultType="com.zibo.mybatis_crud.domain.User">
# 使用抽取的sql语句
<include refid="defaultSQL"/>
# select * from user;
</select>

 

 

举报

相关推荐

0 条评论