mybatis连接池
主配置文件SqlMapConfig.xml中的dataSource标签,type属性就是表示采用何种连接池方式。type属性的取值:
1.POOLED 采用传统的javax.sql.DataSource规范中的连接池,mybatis中有针对规范的实现
2.UNPOOLED 采用传统的获取连接的方式,虽然也实现Javax.sql.DataSource接口,但是并没有使用池的思想。
3.JNDI 采用服务器提供的JNDI技术实现,来获取DataSource对象,不同的服务器所能拿到DataSource是不一样。
注意:如果不是web或者maven的war工程,是不能使用的。 我们课程中使用的是tomcat服务器,采用连接池就是dbcp连接池。
<dataSource type="POOLED">
<property name="driver" value="${jdbc.driver}"></property>
<property name="url" value="${jdbc.url}"></property>
<property name="username" value="${jdbc.username}"></property>
<property name="password" value="${jdbc.password}"></property>
</dataSource>
Pooled 底层采用ArrayList 原理 并且保证队列是线程安全的 先从 空闲池中找,没有再从活动池中找 一个最先进入的(最老的) 返回
自动提交
读取配置文件,生成字节输入流
in = Resources.getResourceAsStream("SqlMapConfig.xml");
SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(in); 2.获取SqlSessionFactory
sqlSession = factory.openSession(true); 获取SqlSession对象,设置自动提交
userDao = sqlSession.getMapper(UserDao.class); 获取dao的代理对象
mybatis基于XML配置的动态SQL
1.模糊查询
1.select % from user where 1=1 and username = xxx and sex = xx 这里的 if 语句 就起到判断有没有值得作用
根据条件查询
<select id="findUserByCondition" resultMap="userMap" parameterType="user">
select * from user where 1=1
<if test="userName != null">
and username = #{userName}
</if>
<if test="userSex != null">
and sex = #{userSex}
</if>
</select>
where 1 =1sql语句 可以换成 where 标签
<select id="findUserByCondition" resultMap="userMap" parameterType="user">
select * from user
<where>
<if test="userName != null">
and username = #{userName}
</if>
<if test="userSex != null">
and sex = #{userSex}
</if>
</where>
</select>
2.in查询
1. 在mybatis xml sql 里也可以使用一个 集合 作为提交 select * from user where id in (45,46,48)
1.创建一个 对象 一个list 属性存放 id 集合
public class QueryVo {
private List<Integer> ids;}
2.配置xml的 select语句 参数是
<select id="findUserInIds" resultMap="userMap" parameterType="queryvo">
select * from user
<where>
<if test="ids != null and ids.size()>0">
<foreach collection="ids" open="and id in (" close=")" item="uid" separator=",">
#{uid} uid与items 名字一样
</foreach>
</if>
</where>
</select>
3.测试语句
public void testFindInIds(){
QueryVo vo = new QueryVo();
List<Integer> list = new ArrayList<Integer>();
list.add(41);
list.add(42);
list.add(46);
vo.setIds(list);
List<User> users = userDao.findUserInIds(vo); 5.执行查询所有方法
for(User user : users){
System.out.println(user);
}}
3.提取重复sql 语句
<sql id="defaultUser">
select * from user
</sql>
<include refid="defaultUser"></include> 这样就引入 上面的sql语句了