连接池
1、连接池:
在实际开发中都会使用连接池
因为它可以减少我们获取连接所消耗的时间
2、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连接池
MyBatis中的事务
什么是事务
事务的四大特性ACID
不考虑隔离性会产生的3个问题
解决办法:四种隔离级别
它是通过sqlsession对象的commit方法和rollback方法实现事务的提交和回滚
动态SQL语句
if标签
在dao接口中准备一个方法
List<User> findBySex(User user);
配置文件中
<!-- 这里在核心配置文件中配置了别名 -->
<select id="findBySex" resultType="user" parameterType="user">
select * from user where 1=1
<!-- 这里的sex是user中的属性 -->
<if test="sex != null">
<!-- 这里前面的是数据库中的属性,后面的sex是user中的属性 -->
and sex = #{sex}
</if>
</select>
where标签
在上面的sql语句中需要准备一个where关键词用来连接sql语句
同时也可以使用where标签来连接条件查询
<select id="findBySex" resultType="user" parameterType="user">
select * from user
<where>
<if test="sex != null">
and sex = #{sex}
</if>
</where>
</select>
这样就不需要在上面写一个where关键词了
foreach标签
可以支持子查询
先将需要查询的数组封装到一个对象内
package com.tianqicode.domain;
import java.util.List;
public class QueryVo {
private List<Integer> ids;
public List<Integer> getIds() {
return ids;
}
public void setIds(List<Integer> ids) {
this.ids = ids;
}
}
dao接口定义一个方法
List<User> findByList(QueryVo queryVo);
配置文件中
<select id="findByList" resultType="user" parameterType="queryVo">
select * from user
<where>
<if test="ids != null and ids.size() > 0 ">
<foreach collection="ids" open="and id in (" close=")" item="id" separator=",">
<!-- 这里的id要与item属性中的值一致 -->
#{id}
</foreach>
</if>
</where>
</select>
测试类
@Test
public void testFindByList() {
QueryVo queryVo = new QueryVo();
List<Integer> ids = new ArrayList<Integer>();
ids.add(1);
ids.add(2);
ids.add(3);
queryVo.setIds(ids);
List<User> users = userDao.findByList(queryVo);
for (User user : users) {
System.out.println(user);
}
}