MyBatis连接池技术
- 在SqlMapConfig.xml配置文件中,通过
<dataSource type="pooled">
实现连接池配置
连接池的分类
- unpolled 不使用连接池的数据源
- polled 使用连接池的数据源
- jndi 使用jndi实现的数据源
数据源的配置
<!-- 配置数据源(连接池)信息 -->
<dataSource type="POOLED">
<property name="driver" value="${jdbc.driver}"/>
<property name="url" value="${jdbc.url}"/>
<property name="username" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
</dataSource>
- MyBatis 在初始化时,根据的 type 属性来创建相应类型的的数据源 DataSource,即: type=”POOLED”:MyBatis 会创建 PooledDataSource 实例 type=”UNPOOLED” : MyBatis 会创建 UnpooledDataSource 实例 type=”JNDI”:MyBatis 会从 JNDI 服务上查找 DataSource 实例,然后返回使用。
DataSource的存取
- MyBatis定义了抽象的工厂接口:DataSourceFactory,通过接口的getDataSource()返回数据源DataSource
连接的获取过程
- 当我们需要创建 SqlSession 对象并需要执行 SQL 语句时,这时候 MyBatis 才会去调用 dataSource 对象 来创建java.sql.Connection对象。也就是说,java.sql.Connection对象的创建一直延迟到执行SQL语句 的时候。
MyBatis的事务控制
MyBatis的事务提交方式
- 实际是调用JDBC的setAutoCommit()来实现事务控制,这是因为在连接池取出的连接,都会将调用connection.setAutoCommit(false),因此必须使用sqlsession.commit()方法。
//4.创建 SqlSession 对象
session = factory.openSession(true);
此时事务设置成自动提交
动态Sql语句
标签
- 根据实体类的不同取值,使用不同的sql语句来查询
- 需求: 如果ID不为空时根据ID查询,如果username不为空时还需要加入用户名作为条件
持久层Dao接口
/**
* 根据用户信息,查询用户列表
* * @param user
* * @return */
List<User> findByUser(User user);
持久层Dao映射配置
<select id="findByUser" resultType="user" parameterType="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 属性中写的是对象的属性名,如果是包装类的对象要使用 OGNL 表达式的写法。
测试
@Test public void testFindByUser() {
User u = new User();
u.setUsername("%王%");
u.setAddress("%顺义%");
//6.执行操作
List<User> users = userDao.findByUser(u);
for(User user : users) {
System.out.println(user); }
}
where标签
- 为了简化扇面where 1=1的条件拼装,采用where简化开发
持久层Dao映射配置
<!-- 根据用户信息查询 -->
<select id="findByUser" resultType="user" parameterType="user">
<include refid="defaultSql"></include>
<where>
<if test="username!=null and username != '' ">
and username like #{username}
</if>
<if test="address != null">
and address like #{address}
</if>
</where>
</select>
foreach标签
- 需求:传入多个id查询用户信息,用下面两个sql语句实现
SELECT * FROM USERS WHERE username LIKE '%张%' AND (id =10 OR id =89 OR id=16)
SELECT * FROM USERS WHERE username LIKE '%张%' AND id IN (10,89,16)
- 这样在范围查询时,就要将一个集合中的值,作为参数动态添加进来。
在QueryVo中加入一个List集合用于封装参数
public class QueryVo implements Serializable {
p