Mybatis的连接池技术
连接池技术简介
Mybatis是一个优秀的持久层框架,由于涉及到要对数据库进行操作,所以必然需要建立跟数据库的连接才能对数据库进行操作,获取数据库连接的技术可分为两种:使用连接池技术和不使用连接池技术。 因为数据库连接是一种昂贵的资源,为了降低操作时在获取数据库连接的时候所产生的时间损耗,通常开发中都会用到连接池技术,这样在程序刚开始运行的时候就初始化创建了预定数量的连接,统一存储在一个容器中,也就是连接池,统一调度管理,这样能极大的提高我们系统的损耗以及运行效率。其原理如下:
在JavaWeb的学习中,学习到了比较常见的两个连接池就是,C3P0和DBCP,而Mybatis也有自己的连接池技术,在 Mybatis 的 SqlMapConfig.xml 配置文件中, 通过< dataSource type=”pooled”>来实现 Mybatis 中连接池的配置。
Mybatis的数据源分类
Mybatis是一个优秀的持久层框架,但凡是涉及到与数据库操作的都需要用到数据源,Mybatis自然也不例外,在Mybatis中为我们内置了三种类型的数据源,分别是POOLED、UNPOOLED、JNDI,如图:
在上图中,POOLED和UNPOOLED所属的类型分别是PooledDataSource 、UnpooledDataSource,它们都实现了 java.sql.DataSource 接口,但其实说到底连接池只是提供了一种缓存连接池的机制,它内部还是通过UnpooledDataSource来创建数据库的连接,所以在PooledDataSource中还是定义了一个UnpooledDataSource的引用。
Mybatis的数据源配置
Mybatis的数据源配置是在SqlMapConfig.xml文件中实现的,具体的实现代码如下:
<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>
也就是通过dataSource type属性来定义,可将其定义为:POOLED、UNPOOLED、JNDI。Mybatis会根据type所指的值来创建相应的实例,当type指定类型为JNDI的时候, MyBatis 会从 JNDI 服务上查找 DataSource 实例,然后返回使用。
Mybatis 自动提交事务的设置
Mybatis默认情况下是关闭事务的自动提交的,但是我们可以根据实际开发的需要来更改这个属性,只需要在sqlSession中设置即可,当设置为true即位自动提交,但实际的开发中还是手动提交用得比较多。
@Before
public void init() throws Exception{
is= Resources.getResourceAsStream("sqlMapConfig.xml");
SqlSessionFactory factory= new SqlSessionFactoryBuilder().build(is);
//在使用SqlSessionFactory获取session的时候可闯入Boolean类型的参数,true则为自动提交,false则手动提交
sqlSession=factory.openSession(false);
studentDao=sqlSession.getMapper(StudentDao.class);
}
@After
public void destory()throws Exception{
//手动提交事务
sqlSession.commit();
sqlSession.close();
is.close();
}
Mybatis 的动态 SQL 语句
在实际开发的过程中,有些时候业务逻辑复杂时,需要根据传入的参数进行判断,从而对SQL语句进行修改,例如为了统一对数据库进行查询操作的语句(模糊查询,根据某一字段查询等),我们只需要定义一条最基本的查询所有的语句,然后根据传入的参数对sql语句进行条件的添加,这时我们的 SQL 是动态变化的,此时在前面的学习中我们的 SQL 就不能满足要求了。
动态 SQL 之< if>标签
我们根据实体类的不同取值,使用不同的 SQL 语句来进行查询。比如在 id 如果不为空时可以根据 id 查询,如果 username 不同空时还要加入用户名作为条件。这种情况在我们的多条件组合查询中经常会碰到。
例如我在像数据库查询学生,可能是模糊查询,可能是根据id,名字查询,则可以像如下定义:
studentDao.xml
<select id="findByStudent" resultType="student" parameterType="student">
select * from student where 1=1
<if test="name!=null and name!=''">
and name like #{name}
</if>
<!--注意在比较数值的时候要判断为null的情况,否则当我们没有给id赋值的时候会查询不出结果,
因为此时id值为null,在数据库中查不到id值为null的情况-->
<if test="id!=0 and id!=null">
and id=#{id}
</if>
<if test="age!=0 and age!=null ">
and age =#{age}
</if>
</select>
studentDao
/**
* 查询所有
* @return
*/
public List<Student> findByStudent(Student student);
以上就是关于动态查询的配置定义,实际中我们需要修改什么查询条件都可以自定义,如下:
@Test
public void findAll(){
Student student=new Student();
student.setId(2);
List<Student> list =studentDao.findByStudent(student);
for(Student s:list){
System.out.println(s);
}
}
动态 SQL 之< where>标签
在前面的代码中,为了给后面可能出现的查询语句的条件加上一些限定的条件,需要在sql语句后面加上 where 1=1,Mybatis中的where标签可以代替这个语句,使用如下:
<select id="findByStudent" resultType="student" parameterType="student">
<!--这里需要在后面加多一个空格,避免与后面的查询条件直接拼接在一起-->
select * from student
<where>
<if test="name!=null and name!=''">
and name like #{name}
</if>
<if test="id!=0">
and id=#{id}
</if>
<if test="age!=0 ">
and age =#{age}
</if>
</where>
</select>
动态标签之< foreach >标签
当我们以id作为查询条件,并且id是一个集合,也就是要查询这个id集合里面对应的所有学生,它的sql语句是这样的:select * from student where id in(1,2,3,4);
用于动态代理就是如下,
定义QueryVo实体类
public class QueryVo {
private List<Integer> ids;
public List<Integer> getIds() {
return ids;
}
public void setIds(List<Integer> ids) {
this.ids = ids;
}
}
定义dao接口方法
/**
* 通过QueryVo查询
*/
public List<Student> findByQueryVo(QueryVo vo);
对应xml文件
<select id="findByQueryVo" parameterType="QueryVo" resultType="student">
select * from student
<where>
<if test="ids!=null and ids.size>0">
<foreach collection="ids" open="id in(" close=")" item="sid" separator=",">
#{sid}
</foreach>
</if>
</where>
</select>
测试方法
@Test
public void findByQueryVO(){
QueryVo vo=new QueryVo();
List<Integer> ids=new ArrayList<Integer>();
ids.add(1);
ids.add(2);
ids.add(4);
ids.add(5);
vo.setIds(ids);
List<Student> students=studentDao.findByQueryVo(vo);
for (Student student :students){
System.out.println(student);
}
}
将以上所有的查询语句整合成一个
QueryVo实体类代码
public class QueryVo extends Student{
private List<Integer> ids;
public List<Integer> getIds() {
return ids;
}
public void setIds(List<Integer> ids) {
this.ids = ids;
}
}
dao层代码
/**
* 通过QueryVo查询
*/
public List<Student> findByQueryVo(QueryVo vo);
XML文件代码
<select id="findByQueryVo" parameterType="QueryVo" resultType="student">
select * from student
<where>
<if test="name!=null and name!=''">
and name like #{name}
</if>
<if test="id!=0">
and id=#{id}
</if>
<if test="age!=0 ">
and age =#{age}
</if>
<if test="ids!=null and ids.size>0">
<foreach collection="ids" open="id in(" close=")" item="sid" separator=",">
#{sid}
</foreach>
</if>
</where>
</select>
测试类代码
@Test
public void findByQueryVO(){
/* QueryVo vo=new QueryVo();
List<Integer> ids=new ArrayList<Integer>();
ids.add(1);
ids.add(2);
ids.add(4);
ids.add(5);
vo.setIds(ids);
List<Student> students=studentDao.findByQueryVo(vo);
for (Student student :students){
System.out.println(student);
}*/
QueryVo vo=new QueryVo();
Student student=new Student();
student.setId(2);
List<Student> list =studentDao.findByQueryVo(vo);
for(Student s:list){
System.out.println(s);
}
}
Mybatis的多表查询
一对多查询
在学生与选课的关系中,这里假设一个学生能选多门课,但是一门课只能有一个学生(假设…),那么在查询的时候可以这么定义。
学生实体类
private int id;
private String name;
private int age;
private List<Course> courses;
//分别生成对应的set和get方法,以及toString,下面省略
XML文件定义
<resultMap id="studentMap" type="student">
<id column="id" property="id"></id>
<result property="name" column="name"></result>
<result property="age" column="age"></result>
<collection property="courses" ofType="course">
<id column="courseId" property="courseId"></id>
<result property="studentId" column="studentId"></result>
<result property="courseName" column="courseName"></result>
</collection>
</resultMap>
<select id="findAll" resultMap="studentMap">
select * from student,course where student.id=course.studentId
</select>
测试类
@Test
public void findAll(){
List<Student> list=studentDao.findAll();
for(Student student:list){
System.out.println(student);
}
}
查询结果
多对一查询
这里还是一样假设一门课只能有一个学生选修,要求查询所有的课程,并且返回该门课程所学修的唯一对应的学生。
课程类Course
public class Course extends Student {
private int courseId;
private int studentId;
private String courseName;
//省略所有set和get方法
@Override
public String toString() {
return "Course{" +
"courseId=" + courseId +
", studentId=" + studentId +
", courseName='" + courseName + '\'' +
'}'+ super.toString();
}
}
CourseDao.xml
<select id="findAll" resultType="course">
select * from course,student where course.studentId=student.id
</select>
本博客纯属个人学习笔记,学习资源来自黑马训练营,如有错误,感激指正